Home > Blockchain >  Is there a way to reference individual instantiated cloned objects?
Is there a way to reference individual instantiated cloned objects?

Time:08-24

If I instantiate multiple instances of the same, lets say, ball object and there ends up being 20 balls, how do I reference one specifically? For example, if I wanted to change the color of one ball clone, destroy a specific clone, or get access to an individual ball clone's specific variables that are attached to it, how would I go about doing that?

All cloned objects just appear in the hierarchy as "ballgameobject(clone)". Is there a way to tell them apart?

CodePudding user response:

You can give each Ball a unique identifier during their initialization.

public class Ball : MonoBehaviour
{
    private readonly Guid id = Guid.NewGuid();

    public Guid Id => id;
}

This id can then be used to uniquely identify specific ball instances.

public class BallManager
{
    private readonly Dictionary<Guid, Ball> instances = new Dictionary<Guid, Ball>();

    public Ball CreateBall(Ball prefab)
    {
        var result = Object.Instantiate(prefab);
        instances[result.Id] = result;
        return result;
    }

    public void SetBallColor(Guid ballId, Color color)
    {
        instances[ballId].GetComponent<Renderer>().material.color = color;
    }

    public void DestroyBall(Guid ballId)
    {
        Object.Destroy(instances[ballId]);
        instances.Remove(ballId);
    }
}

UPDATE: If the id does not need to persist between sessions then you could actually also just use Object.GetInstanceID().

private readonly Dictionary<int, Ball> instances = new Dictionary<int, Ball>();

public Ball CreateBall(Ball prefab)
{
    var result = Object.Instantiate(prefab);
    instances[result.GetInstanceID()] = result;
    return result;
}

CodePudding user response:

It sounds like you're working in Unity. You can do this with each individual gameObject in Unity. You should also rename them all in Unity so that they can be told apart.

CodePudding user response:

You can save the clones in an array to reference then later like this:

void Start()
{
    GameObject ball = new GameObject("Ball");   
    GameObject[] clones = new GameObject[20];

    for(int i = 0; i < 20; i  )
    {
        clones[i] = GameObject.Instantiate(ball);
        clones[i].name = $"Ball_{i}";
    }

    //With the array indexer you can access each clone and can do whatever you want with it.
    Destroy(clones[5]); // Destroys the fifth gameobject
}
  • Related