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?

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.