Best practice for getting a reference? Code injection?

DavidC

Active member
I've done several forms of referencing and none of them really sit right with me. Of course, "GetComponent" is easiest, but it's also not performant and it can be broken if you change the hierarchy of game objects, which can be a concern in some situations.
There's the code injection method, but for runtime instantiating of items (like a gun), I'm not really seeing a good way to do it. Just in case it isn't clear what I mean, here's the explanation from Brackey's.


Code:
//  If the objects are instantiated prefabs...
//... then you can use a form of injection after you call Instantiate:
// SomeScript.cs

public GameManager TheManager { get; set; }


// GameManager.cs
var clone = Instantiate(prefab);
clone.GetComponent<SomeScript>().TheManager = this;

Also related to this specific instance, but is there a "item is used" function somewhere (In Inspector) that I'm missing. There's "OnRayCastHit()" on "Shootable Weapon" but the function I want to call in my script should be called when the item is used, regardless if there's a hit.
 
Last edited:
Top