- Home /
Replace instantiated objects in an array
I have an array of instantiated objects. Now as I have an in game shop I would like to replace those objects with another prefab that was selected in shop. Is it possible to just assign a different prefab to already instantiated objects from an array. Or is it possible to instantiate empty game objects and then just assign different prefabs later?
Answer by Jebulan · Jan 03, 2019 at 06:12 PM
If I understand you question correctly: When you instantiate a new object, it returns a reference to that new gameObject. array[x] = Instantiate(name,options); Replacing an item in an array should be similar to how you originally populated it.
However I don't believe Unity will allow you to apply (or change) a prefab to an existing gameObject. Mapping variables between different prefabs that may have different scripts attached is problematic.
You can create empty gameObjects and instantiate other gameObjects inside of it, which is may be what you are after?
At the beginning of the game I have an array of gameObjects that will be used in the game. Player can buy different objects from the shop, so what I want to do is replace those old objects in that array with the new bought one.
Assu$$anonymous$$g the array of gameObjects references existing objects in the scene: In code you will need to instantiate a new object and replace the old object with the new object in the array.
newObject = Instantiate(name,options);
oldObject = array[x];
(You may need to match location,rotation.)
newObject.transform.position = oldObject.transform.position
array[x] = newObject;
destroy(oldObject);
Even though we replaced the object in the array, the old object will still exist in the scene and will need to be destroyed.
Ultimately the scene is where the gameObject is stored, the array is just a reference to it.
Perhaps there's a better way, but afaik this would be the way to do it.
I was kind of looking for a way to not destroy objects all the time, just replace them..
Wasn't sure how your project is setup. Lot's of ways to approach this.
If they don't have visible objects, there's no need to destroy them other than cleaning things up. And you don't have to match position either, unless it affects game play.
$$anonymous$$y first reply should work in that case. (Instantiate the object into the array slot).
You could also have the objects in the shop already created in the scene, and in that case you could just swap array references. myobjects[x] = shopObjects[y]
The problem lies in trying to apply a prefab to an instantiated object. Which I don't think can be done.
Hope this helps