- Home /
Accessing variable in a specific instance of a prefab
I have a script on Object_A called script_A. It instantiates instances of prefab Object_B which has script on it called script_B. This script contains an public integer variable called randomNumber.
Let’s say I’ve created 3 instances of Object_B and each instance’s randomNumber is unique.
How to I retrieve each specific instance’s unique randomNumber in script_A?
Here's script_A:
public Rigidbody Object_B;
public int randomNumber1;
public int randomNumber2;
public int randomNumber3;
void Update ()
{
if (Input.GetButtonDown ("Fire1"))
//on left click, instantiate an instance of Object_B at Object_A's location+rotation
{
Rigidbody Object_B_Instance;
Object_B_Instance = Instantiate (Object_B, transform.position, transform.rotation) as Rigidbody;
}
randomNumber1 = GameObject.Find("Object_B (clone)").GetComponent<script_B>().randomNumber;
randomNumber2 = GameObject.Find("Object_B (clone)").GetComponent<script_B>().randomNumber;
randomNumber3 = GameObject.Find("Object_B (clone)").GetComponent<script_B>().randomNumber;
}
Here's script_B
public int randomNumber;
void Start ()
{
randomNumber = Random.Range (1, 10);
}
I dont know if it will work for your need.But you can try this.
While instantiating you can define the parent. Instantiate(Object_B, transform.position, transform.rotation,holder.transform); holder is my parent object.
Then obtain the info from accessing its child objects. which will be prefabs you instantiated.
Answer by Mehul-Rughani · Dec 05, 2017 at 11:55 AM
Hello @GeorgeLuther,
Please check this solution
In Script_A script take one list of Script_B Component and when you instantiate B object add it to the list and access it wherever you want.
public class Script_A : MonoBehaviour
{
public GameObject prefab;
public List<Script_B> generatedObjects = new List<Script_B> ();
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space)) {
for (int i = 0; i < 3; i++) {
GameObject go = Instantiate (prefab, transform.position, transform.rotation)as GameObject;
Script_B secondObject = go.GetComponent<Script_B> ();
generatedObjects.Add (secondObject);
}
}
if (Input.GetKeyDown (KeyCode.A)) {
for (int i = 0; i < generatedObjects.Count; i++) {
Debug.Log (generatedObjects [i].randomNumber);
}
}
}
}
and
public class Script_B : MonoBehaviour
{
public int randomNumber;
// Use this for initialization
void Start ()
{
randomNumber = Random.Range (1, 10);
}
// Update is called once per frame
void Update ()
{
}
}
Hope you are looking for this
Regards
Your answer
Follow this Question
Related Questions
Instantiate a COMPLETELY Unique Instance of an Object 1 Answer
How to get the instance of a ScriptableObject 3 Answers
Duplication(instance) re-create deleted children 0 Answers
Updating a variable on a script in an instanced object 1 Answer
Projectiles trigger affecting other projectiles of same prefab - C# 0 Answers