Question by
unity_3rwby93b8roxIQ · Mar 09, 2021 at 04:28 PM ·
getcomponentaccessing from any script
Access variable from another script without GetComponent
I have a scene, in which I instantiate an object depending on some criteria (it can instantiate prefab1 or prefab2). They are similar prefabs, just different graphics and stuff like that. On each of the prefab I have this script, where I link stuff in the editor for each prefab:
public class Helper : MonoBehaviour {
[SerializeField] public ShotsController ShotsController;
[SerializeField] public Animator Animator1;}
Purpose of this is to get different animators and ShotsController depending on which prefab is instantiated. Instantiation of object looks like this, and below I get the stuff that I need from the prefab.
public class StageController : MonoBehaviour {
[SerializeField] private GameObject object1;
[SerializeField] private GameObject object2;
...
private void SetScene(GameObject object) {
GameObject stage = Instantiate(object, Vector3.zero, Quaternion.identity);
var object = stage.GetComponent<Helper>();
ShotsController = stage.ShotsController;
Animator= stage.Animator1;}
This works fine, but I am wondering if there is a better way to do that? So is there a way to reference Animator1, without using GetComponent? :)
Comment
Your answer
