- Home /
Find a variable using a string
I want to be able to use a generated string to identify which GameObject the supplied prefab is assigned to in a method. The GameObjects are labelled Prefab1, Prefab2, Prefab3, etc. I have a couple lines that create a string that says Prefab(ID) dynamically, but I don't know how to convert that into a GameObject. Any thoughts?
Answer by toddisarockstar · Jul 30, 2017 at 09:41 AM
there are several ways. you have to think outside the box a bit. i would make sure you get your prefabs or game objects into arrays or lists for easy checking. for example purpose i will assume there are game objects in your scene called prefab0,prefab1 and prefab 2......ect in programming always start at zero..... never 1! if you are just looking to refer to them with numbers you could do something like this:
using UnityEngine;
using System.Collections;
//you need this line at the top
using System.Collections.Generic;
public class NameOfScriptGoesHere : MonoBehaviour {
List<GameObject> mydudes = new List<GameObject>();
void Start(){
int i=0;
while(GameObject.Find(i+"prefab")){
mydudes.Add(GameObject.Find(i+"prefab"));
i++;}
//now you can refer to them with a number like this:
mydudes [1].transform.renderer.material.color = Color.red;
mydudes [2].transform.renderer.material.color = Color.blue;
}
}
Does this work on objects that aren't currently in the scene? $$anonymous$$y intuition tells me that GameObject.Find doesn't work on unloaded objects, but I might be wrong here.
Your answer
Follow this Question
Related Questions
Using Resources.load with a variable 1 Answer
How to assign a gameObject to prefab (in-game via code)? 1 Answer
How can i set a prefab to x=0 and y=0. 3 Answers
[Solved]Instantiating prefab from a script and destroy it from another one 2 Answers
How to assign a gameobject to a script that is added dynamically 1 Answer