- Home /
Using strings to refrence gameobjects in C#
Is there a way to refrence gameobjects using a string? For instance, something like this
GameObject machineGun;
GameObject weaponSlot1;
// playerPrefs.GetString("weaponName") = machineGun for this example
weaponSlot1 = playerPrefs.GetString("weaponName");
I can't seem to figure out how to do this. I don't want to actually convert anything, just use the string to reference the gameObject.
Thanks for any help!
Expanding on @Ngoc Ngo's answer, you can give each game object a unique name or a unique tag. Then as he suggests, you can use GameObject.Find(). Or if using a tag, GameObject.FindWithTag().
Big question is why? The approach will depend on the desired result
To add to the ideas being thrown around you could use a dictionary.
Dictionary<string, GameObject>
Thanks for the answers, I am aware of GameObject.Find() but that is not quite what I had in $$anonymous$$d for this scenario.
Basically all I want to do is use a string like I would use any other snippet of code. so something like this (P.S. this is completely useless code, its just for clarification)
public string temp = "hello";
public GameObject hello;
public GameObject helloPart2;
helloPart2 = hello;
/* or this is what I am trying to do, it would accomplish the same as the above */
helloPart2 = temp;
Hopefully that makes sense : )
Edit: @Bored$$anonymous$$ormon
I am trying to basically assign an inventory object to a players equipped items. So I have like 20+ items, and well, here is an example of how I am doing this now:
if (PlayerPrefs.GetString("lWeapon11Name") == "WoodAxe"){
slot1 = WoodAxe;
}
if (PlayerPrefs.GetString("lWeapon11Name") == "Axe"){
slot1 = Axe;
}
if (PlayerPrefs.GetString("lWeapon11Name") == "$$anonymous$$nife"){
slot1 = $$anonymous$$nife;
}
where if I could use the playerPrefs sting as a reference, I wouldn't have to loop through all the available items, it would just be
slot1 = PlayerPrefs.GetString("lWeapon11Name");
Every so often someone wants to use a string to build a variable or access a variable at runtime. It can't be done is the simple way everyone tries. You would need to build some map between strings and the game objects like the dictionary suggested by @Bored$$anonymous$$orman.