I started learning unity,
I want to add points in the score when an object destroy.
If the object is destroyed, the function returns "true"
I'm trying to use with bool variable in other class like that:
if (hexagon.GetComponent<Hexagon>().HexagonDistroy == true)
But I have an error message in console:
"object reference not set to an instance of an object"

- 4,888
- 1
- 21
- 32

- 9
- 1
-
NRE (null reference exception) means that the object of which property you're trying to reference does not exist. So in this case, either "hexagon" is null or "GetComponent
()` is null, meaning that the hexagon object doesn't have the Hexagon script attached. You're saying you're destroying objects, so could it be that you're doing `Destroy()` before trying to access it, so that it is null because you've destroyed it? – Fredrik Schön Jul 17 '20 at 12:59
3 Answers
Because when you destroying object you destroying all information about an object include components.
You can check information about that object was destroyed like this:
if(hexagon == null)
points++;

- 479
- 3
- 10
I'm not sure since I haven't used unity in a while and didn't learn it so deeply myself, but I'm pretty sure your hexagon component, or whatever you're throwing into your condition in your if statement is referenced correctly. What this means is that you need to reference it in that class as well.
Although I don't think that's your issue since you titled the thread "Using functions in another class". I assume hexagon is either a class or a function in another class. Basically, to access variables or functions from another class do:
classname.variable //If the variable is a global variable, in other words declared in your class but outside a function
//So if I understand your question correctly, you would do
if(classname.varible == true) {
//code
}

- 34
- 6
It would be good to add more code so we can figure out what it is about. This error occurs when no object reference is made. so be sure the hexagon contains the HexagonDistroy component.

- 44
- 1
- 5
-
and of course there can be no such thing as you wrote. if(hexagon.GetComponent().HexagonDistroy().destroyed == true) – Overact Overact Jul 17 '20 at 12:54
-
you can't check if a component is true, check if it exists if(hexagon.GetComponent().HexagonDistroy() != null) { // do stuff } – Overact Overact Jul 17 '20 at 12:55