- Home /
Accessing a variable from another script without using GetComponent<> c#
Here is the situation. I have a bullet prefab that alters the movement speed of any object with a certain tag. But all the enemies have different movement scripts attached to them. I have the speed variable named exactly the same on every enemy movement script.
so my question is, is there a way for my bullet prefab to look for a particular variable on a gameobject, without Getcomponent. The Reasoning is that i do not want my bullets prefab script to have to run through countless if statements on a collision to find the correct enemy movement script to access the speed variable.
In a perfect case I would like to say something like,
OnCollisionEnter(Collision other) { if(other.tag == "Something") { "get access to the the speed variable of the other gameobject" } }
Answer by Commoble · Jan 29, 2018 at 09:05 PM
You could make all of your enemy scripts child classes of a general Enemy class (i.e. make Enemy extend MonoBehaviour and individual enemy types extend Enemy), then define a getSpeed() method on Enemy and override that function in the subclass scripts. Then just have your bullet script do
Enemy enemyScript = other.GetComponent<Enemy>();
if (enemyScript != null)
{
speed = enemyScript.getSpeed();
}
If you're not familiar with this sort of thing, this is called Polymorphism and it's an important part of C# and other object-oriented languages. Unity provides a few video scripting tutorials on it: see Intermediate Gameplay Scripting; Inheritance, Polymorphism, Member Hiding, Overriding, and probably Interfaces as well.
All that being said, if you need to get a reference to a component on another object, you do need to call GetComponent on it to access that component's methods and fields. However, if you don't need to get any information back out of the object (you just need to make the object do something), you can define your own message event methods (i.e. methods similar to Start, Update, OnCollisionEnter, etc). gameObject.Send$$anonymous$$essage allows will call any method by string on all components in the gameObject; it won't return anything, so it's not useful for this question, but it may be helpful in the future
Your answer
