Setting a Child as a Gameobject

Hello

I know this is probably very easy, but I’ve been stuck on this for awhile now. I’m trying to add a child to a gameobject variable in a script. Basically I’m doing this so I can only allow one voiceline from a character to play at once. So I want to have it so when a gameobject called Death Voiceline spawns and after it’s added to the empty gameobject it is set as the variable I have set. And if that variable has an object in it. The newly added voice line is destroyed.

I can’t figure out how to add the child to the variable however.

public GameObject VoicePlaying;

    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update ()
    {
        if (VoicePlaying != null)
        {
            VoicePlaying = gameObject.transform.FindChild ("Death Voiceline").gameObject;
        }

    }

This is what I’m doing. Anyone have any thoughts?

Thank you

Well…FindChild is deprecated, but it might still work, however, I wouldn’t use it.

However, two issues.

First, doing this in update is bad. If you are instantiating something, you should assign it then. Otherwise, you will constantly be doing this call over and over again.

Second, your check is for VoicePlaying to not be null, which means once something is assigned to it, you want to assign something else to it? I’m not even sure I understand what you are really trying to do to be honest.

1 Like

here is my two cents

//what gameObect has this script?  I assume the parent

public GameObject VoicePlaying; //don't set this via the inspector.  I would like to see it as a private
    // Use this for initialization
    void Start () {
      
    }
  
    // Update is called once per frame
    void Update ()
    {
        if (VoicePlaying != null) //if it's not null
        {
            // it's assigned so do something with it every frame
        }else
        {
            //reassign VoicePlaying to use child gameObect
            VoicePlaying = GameObject.Find(gameObject.name + "/Death Voiceline"); //find and set the child via it's name
            //you can know do some more code here, like set a value in the child
            VoicePlaying.GetComponent<ChildScriptBlaBla>().somevariable = something;
        }
    }
1 Like

Thanks for the reply, sorry I didn’t make much sense there, I was off today haha.I figured out the issue, thanks for your feedback it got me to think of the answer. With telling me that it was a bad idea to use the update.

Thanks for the reply, that is very useful information. Thank you for taking the time to answer my question!