0

So I instantiated an Object but i want to change some of its properties right after instantiating it. So i have to do something like:

Gameobject instantiated.GetComponent<>().property = "example Value";

Here is my code so far:

public void createObject(GameObject obj)
{
    //Debug.Log(pos + i*offset);
     Instantiate(obj, pos + i*offset, obj.transform.rotation).transform.SetParent(GameObject.FindGameObjectWithTag("Canvas").transform, false); 
    i++;
}

if i try to do something like: Gameobject instantiated = Instantiate(obj, pos + i*offset, obj.transform.rotation).transform.SetParent(GameObject.FindGameObjectWithTag("Canvas").transform, false);

it says: "void" cant be converted to "UnityEngine.GameObject".

Are there other ways to do it? Thx for every helpful advice

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • https://docs.unity3d.com/ScriptReference/Object.Instantiate.html - From Description: _"Clones the object original and returns the clone."_ – ProgrammingLlama Nov 20 '21 at 13:08

1 Answers1

2

You need to cache it first, then you can apply any proper changes to it. Like this:

GameObject newObject =  Instantiate(YourPrefab);
newObject.someProp = something;

So in your case, do this:

public void createObject(GameObject obj)
{

 GameObject newObject = Instantiate(obj, pos + i*offset, obj.transform.rotation); 

newObject.transform.SetParent(GameObject.FindGameObjectWithTag("Canvas").transform, false);
    i++;
    }