Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to Set a Variable In an Instantiation

Discussion in '2D' started by CodeUnit07, Aug 31, 2023.

  1. CodeUnit07

    CodeUnit07

    Joined:
    Aug 10, 2023
    Posts:
    11
    Hi guys!

    My question is how to set a variable for every instantiation. I have a script that instantiates blocks that have a certain health value. I want to set the health value in the instantiation. How do I do that?

    Thanks
     
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,343
    Something like this should work:

    Code (CSharp):
    1. GameObject instantiatedObject = Instantiate(prefab, transform.position);
    2.     instantiatedObject.GetComponent<MyScriptOnObject>();
    3.     instantiatedObject.MyFunctionToSetValues();
    Set a local variable and set it equal to the instantiated object. Get the script on your prefab, then call the function you need that sets your value.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,752