How to send info from child script to parent script.

I use this script. However this one looks for a script with that name (MovementPieces). If i use another gameobject with the same script they both act. So how can i use the parent only and not other game object.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Steering : MonoBehaviour
{
    public int Movedir;
    SpriteRenderer spriteRenderer;


    private MovementPieces MP;


    void Start()
    {
     
        GetComponent<CircleCollider2D>().enabled = false;
      MP = FindObjectOfType<MovementPieces>();
        this.spriteRenderer = GetComponent<SpriteRenderer>();
        this.spriteRenderer.enabled = false; // disable the renderer
    }




    // Update is called once per frame
    void Update()
    {

        Physics2D.IgnoreLayerCollision(8, 9);

        if(MP.ShowDir ==true)
        {
            GetComponent<CircleCollider2D>().enabled = true;
            this.spriteRenderer.enabled = true; // disable the renderer
        }
        if (MP.ShowDir == false)
        {
            GetComponent<CircleCollider2D>().enabled = false;
            this.spriteRenderer.enabled = false; // disable the renderer
        }


    
    }
}

On line 18 you are getting your reference to MovementPieces with FindObjectOfType. FindObjectOfType will just get the first MovementPieces it finds anywhere. I wouldn’t use it for this unless there either was only 1 instance of MovementPieces in the entire hierarchy, or it did not matter at all which instance it found.

What you probably want is GetComponent, so you can be specific about where you find it. If the instance you want is attached to the parent GameObject you would change the line to:

MP = transform.parent.gameObject.GetComponent<MovementPieces>();

Note that GetComponent is designed to return null when an instance of what you ask for is not found attached to that specific GameObject. So you either need to be sure an instance will really be there, or you should check for a null result before trying to use it.

1 Like

Thank you for your answer i was looking into it so i used your line in the start function but how to reach and change the variable in that script i use now : if(MP.ShowDir ==true)

I am not familiar with all coding terms yet but i guess somehow i need to use GetComponent again somehow ? Without it i get indeed a Null reference not set to an instant of an object report :slight_smile: Thx again for taking time to answer.

i found the solution and it works.

if(transform.parent.gameObject.GetComponent().ShowDir == true)

good to know how this works now.