I am looking for a way to avoid the use of GetComponent ( ) completely, my language is c#.
Could you please point me in the direction where I should search at, all I need is to reference a script (maybe somehow from an allocated memory), located in a game object.
That is, reference script instance on a game object (maybe through a pointer), perhaps with my own _GetComponent( ) function, to dodge Unity’s API.
Even if you tell me how to open unity’s shipped code with GameObject class code, will mean a lot to my search.
Thank you very much!
EDIT: I’ve added the code, sadly the previous answers aren’t the ones I am looking for The problem is shown in the last 3 lines
using UnityEngine;
using UnityEditor;
using System.Threading
[CustomEditor(typeof(ScriptA))]
public class ScriptAEditor{
//vars declarations
void OnEnable(){
GameObject somevarOfTypeGameObj = (GameObject)target; //This game object will have ScriptZ on it
}
void OnInspectorGUI{
object a1 = somevarOfTypeGameObj;
Thread t1 = new Thread(new ParameterizedThreadStart(functionX));
t1.Start(a1);
}//end onInspectorGUI
void functionX(object _work){
ScriptZ lookat = (ScriptZ)_work; //will not work, as unity says somevarOfTypeGameObject cannot be casted as ScriptZ.
//Default approach is to use standard GetComponent, which won't wok with threads
//threading is highly required as functionX is recursive
//getting component ScriptZ and passing it into the function before the thread starts won't work, since functionX is recursive and
//accesses different instances of scripts from different game objects
}
}
Depends on how flexible you want it to be. In my case, I don’t use to add and remove components that much, so I cache/serialize references to them. Cached references access cost nothing. Normally you would assign at runtime (e.g. Awake) I found interesting doing that at editor time i.e. serialize cached refs. Here’s a basic example to show how it would work (typed directly here, so forgive typos :P)
In this case I’m taking advantage of the Reset callback being called when the behavior is instantiated (that won’t work if the component was previously there. You may want to implement stuff on OnEnable and use ExecuteInEditMode, or create a context menu to reassign references… the implementation is up to you).
Also, Unity’s implementation of GameObject internally have those references serialized (examine a prefab or scene YAML file, or even the UnityEngine assembly). They just don’t expose them in their API.