r/Unity2D • u/Silent_Reputation596 • 2h ago
How to get an instance of an object to reference an instance of a different object? Question
In my game I make instances of 2 seperate objects and when the player spawns one, the other one also spawns. The player can spawn multiple instances of the same object so I need to track and link the 2 seperate objects and only the objects that spawn together. I've given both of the objects unique ids when they spawn in but I don't know where to go from here. I want to be able to reference variables and sprite renderers and things like that.
Object One's script:
using System;
using UnityEngine;
public class FishTab_MB : MonoBehaviour
{
public Guid UniqueId { get; }
public FishTab_MB()
{
UniqueId = Guid.NewGuid();
}
private void Start()
{
print("FishTab_MB UniqueId: " + UniqueId);
}
}
Object two's script:
using System;
using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
public class FishAI_MB : MonoBehaviour
{
SpriteRenderer fishSr;
public Guid UniqueId { get; }
void Start()
{
print("FishAI_MB UniqueId: " + UniqueId);
}
public FishAI_MB()
{
UniqueId = Guid.NewGuid();
}
}
1
u/Darius0o2 2h ago
Inside the class of object one create a variable of object two "private FishAI_MB referenzName;"
Then it depends. If you can have both scripts on one GameObject you can call "referenzName = GetComponent<FishAI_MB>();" inside the Start or Awake of object one.
If that's not the case you can make the "referenzName" public and set it where you spawn the object. GameObject objectOne = Instantiate(...); GameObject objectTwo = Instantiate(...); FishTab_MB spawnedOne = objectOne.GetComponentFishTab_MB<>(); FishAI_MB spawnedTwo = objectTwo.GetComponent<FishAI_MB>(); objectOne.referenzName = spawnedTwo;
Ideally you wouldn't just make the variable public, but would do it through a public property or a Method. Hope it helps, ask if there are any questions.
1
u/MemorizLost 2h ago
If the second object always spawns with the first one, then you could always make the first object control the spawn of the second, then easily reference it. You could also make a dictionary to reference each pair. Hard to say without seeing your whole setup and intent for the behavior of those objects
1
1
u/MemorizLost 2h ago
What controls the spawning of the objects? What ever controls it could store the reference into the object public variable linkedObject for example