- Home /
OnMouseDown() function is not changing gameobject declared outside.
I am using OnMouseDown()
like following
public class Rotateprents : MonoBehaviour
{
GameObject P1;
GameObject C1;
GameObject C2;
void OnMouseDown()
{
if (transform.name.Contains("Parent"))
{
P1 = transform.gameObject;
C1 = P1.transform.GetChild(0).gameObject;
C2 = P1.transform.GetChild(P1.transform.childCount - 1).gameObject;
Debug.Log(C1);
}
else if (transform.name.Contains("child"))
{
P1 = transform.parent.gameObject;
C1 = P1.transform.GetChild(0).gameObject;
C2 = P1.transform.GetChild(P1.transform.childCount - 1).gameObject;
}
}
public void rotateobj()
{
Debug.Log(C1);
}
}
Gameobject C1 is empty in rotateobj(). Why?
Please try to rewrite your question, it is hard to understand what you mean.
I'm not 100% sure where you have this script attached, I'm guessing to both the parent and the child objects? I'm presu$$anonymous$$g that the objects have colliders attached to them directly? What happens in the case of clicking the child, can you log that too?
The most likely reason if you have colliders attached is that the names aren't passing the name checks (also consider tagging them for improved performance compared to string comparisons).
Inside the OnMouseDown()
"C1" is not empty but inside rotateobj() it is Null. And rotateobj() function is assigned to button which i press after OnMouseDown() Function is executed
Answer by endasil_unity · Dec 29, 2021 at 01:44 PM
C1 can only be null in rotateobj if:
it was assigned null in OnMouseDown
The object C1 points to has been Destroyed
OnMouseDown was called after rotateobj
You're calling rotateobj on another copy of your script than the one you called OnMouseDown on.
We would need more info about your scene setup showing what scripts are attached to what gameobject and how the functions are called to know which one, but verify that the script your setting C1 in is actually the same you're checking it in.
Change Debug.Log(C1); to Debug.Log(C1 + "id " + this.GetInstanceId()); to see if the id is the same in both OnMouseDown and rotate.