Home > Software engineering >  Updating values in a component in instantiated gameobject in unity
Updating values in a component in instantiated gameobject in unity

Time:01-26

Hi i have a Robot Prefab, with a NPC script that is linked to dialogue sentences.

I am retrieving the information about dialogues (using a loader script) from a server API, and then instantiating both the robot gameobject and the sentences. For example for instantiating the gameobject:

GameObject newObject = GameObject.Instantiate(Resources.Load("prefabs/"   item.gameObject.name) as GameObject, parentProps);
newObject.transform.localPosition = new Vector3(loaded.x, loaded.y, loaded.z);
newObject.transform.localEulerAngles = new Vector3(0, 90f, 0);

However, i do not know how to access the dialogue and update it. Could someone tell me how to update the instantiated value of the sentences here (marked it with red arrows on the image below)?

May be a basic question, but am new. Thanks!

enter image description here

CodePudding user response:

You can create a public function in Npc class and call it after you instantiated it.

GameObject newObject = GameObject.Instantiate(Resources.Load("prefabs/"   item.gameObject.name) as GameObject, parentProps);
newObject.transform.localPosition = new Vector3(loaded.x, loaded.y, loaded.z);
newObject.transform.localEulerAngles = new Vector3(0, 90f, 0);
newObject.GetComponent<Npc>().UpdateDialog();

CodePudding user response:

On your Robot GameObject use GetComponent to get the NPC script object. Then you are able to modify the values. Make sure that the visibility of your variables is either public or has getters/setters.

  •  Tags:  
  • Related