Can we anyhow store a prefab in a list when we collide into the instance of that prefab casted as gameObject?
I want a list to store the original prefab of a game object when my player runs into that game object instance of a prefab.
Answer by streeetwalker · Sep 09, 2020 at 07:04 AM
@kushalagrawal890, Check out PrefabUtility.GetPrefabParent -- look at the documentation on this - it is supposed to return exactly what you want...
[Edit & correction]
This is an editor only function. There is no way to programmatically determine what prefab an object instance was Instantiated from. This does work in an Editor script, but not at runtime.
You can, at the time you create the instance store a reference to the prefab in a script on the object. (probably the simplest method to track and object and it's prefab.)
So, create a script on your instanced object with a public GameObject myPrefab field.
Then at the time you Instantiate the prefab:
// assume you have a prefab reference in a public field thusly:
public GameObject prefabObject;
// then assume you have a script "ObjectScript.cs" as a
//component on the prefab that contains this:<br><br>
public GameObject prefabObject;
// then where you instantiate the object
GameObject gO = (GameObject) Instantiate( prefabObject );
ObjectScript oS = gO.GetComponent<ObjectScript>();
// now store a reference to the prefab on the newly
//instantiated gameObject:
oS.prefabObject = prefabObject;
There are definitely other ways to do it. For example, if you want to store prefabs in a list, and in a corresponding list the gameObject instances, and associate the two list by their indices, for one.
Thank you for helping me. But I seem to encounter a problem. I want a list to contain prefabs so I made the list this way List
We'd have to see your code at this point - it's not clear what you mean.
public List<UnityEngine.Object> team$$anonymous$$ates = new List<UnityEngine.Object>();
public void AddTeammate(UnityEngine.Object teammate)
{
team$$anonymous$$ates.Add(teammate);
}
AddTeammate(PrefabUtility.GetPrefabParent(this.gameObject));
OK, so you're getting an error? What exactly is the error and exactly which line of code is generating it?
I am not getting any error it's just that the list increments by 1 but doesn't store any prefab