Leonardo Biagi
Leonardo Biagi

Reputation: 11

Instantiate a gameObject and give it a name

I would like to Instantiate a gameObject and give it a specific name in the hierarchy, because it gives by default "gameObject(clone)", but I would like to know if there is a way to make it name the spawned object just "gameObject" and not "gameObject(clone)". Thank you

Upvotes: 1

Views: 3183

Answers (2)

Vionix
Vionix

Reputation: 590

You can assign the instantiate Prefab to a game object and then change the name of the game object.

Here is a sample code

my_spawned=Instantiate(prefab,transform.position,Quaternion.identity) as GameObject;
my_spawned.name="Myobject";

Source: https://vionixstudio.com/2019/11/27/unity-instantiate/

Upvotes: 0

Sisus
Sisus

Reputation: 729

You can create an extension method that clones an object and then sets the name of the clone to match the name of the original object.

using UnityEngine;

public static class ObjectExtensions
{
    public static TObject Instantiate<TObject>(this TObject original) where TObject : Object
    {
        TObject result = Object.Instantiate(original);
        result.name = original.name;
        return result;
    }
}

Usage:

GameObject clone = gameObject.Instantiate();

Upvotes: 2

Related Questions