1

I am new to unity and I've been working on a menu system. But to do this I want to access a child's method from the parent object.

My Parent Object.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems; // 1

public class buttonAnimation : MonoBehaviour
, IPointerEnterHandler
, IPointerExitHandler
{
    private bool mouseOver = false;
    private Vector3 startPos;
    private Vector3 offsetPos;
    private int offset = -20;//Change this to set the offset Amount.
  //  private script mousePresent;

    void Start(){
        startPos = transform.position;
        offsetPos = startPos;
        offsetPos.x = offsetPos.x + offset;
//script = gameObject.tranform.GetChild(0).GetComponent<mousePresent>();

    }

    void Update(){

        bool s = transform.GetChild(0).GetComponent<mousePresent>().mouseHere; //This line is the error causing one
        Debug.Log(s);
        if(s == false){
            mouseOver = false;
        }

        //if(script.getMousePresent() == false){
       //   mouseOver = false;
       // }

    }

}

Child Object Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems; // 1

public class mousePresent : MonoBehaviour
{
    public bool mouseHere = false;
    void Start()
    {


    }

    public bool getMousePresent(){

        return mouseHere;
    }
}

I've been trying to get access the the mouseHere variable in the child object. I've tried it as a public variable and private one with a get method. But the same error occurs in both events.

That being when I try to run things in unity.

NullReferenceException: Object reference not set to an instance of an object buttonAnimation.Update () (at Assets/Main Menu/Script/buttonAnimation.cs:25)

SeanAbner
  • 63
  • 6
  • Name your classes with a leading UpperCase character, following standard naming guidelines. As to your error, see the dupe target (which is caused by one of two things: getting the wrong child or the script is not attached to that object). – Draco18s no longer trusts SE Nov 26 '19 at 17:53

1 Answers1

1

You can use GetComponentInChildren instead

Returns the component of Type type in the GameObject or any of its children using depth first search. A component is returned only if it is found on an active GameObject.

For example:

void Start(){
    //... your code
    script = gameObject.GetComponentInChildren<mousePresent>();
}

Note: Also be sure that your child object is Active!

Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63