Unity GetComponent Script?
I was trying to make an rts like game where I can move multiple units at the same time & I got the movement & selection working but now I would like to put them together. So when you right click you have a raycast to get world position then inside that I have:
for (int i = 0; i < selectedUnits.Count; i++)
selectedUnits[i].GetComponent(s_Unit).MoveMethod(hit.point.x, hit.point.y, hit.point.z);
The idea is to send the position to all selected units in the arraylist by getting the s_Unit script they all have & telling it to run their MoveMethod so that only the selected units will get the command & later I can offset the value per unit etc, but I can't get the thing to work I have tried I bunch of things like .transform.Find("s_Unit"). & (). .
Any help would be appreciated.
Answer by OctoMan · Nov 05, 2015 at 08:21 PM
for (int i = 0; i < selectedUnits.Count; i++)
selectedUnits[i].GetComponent<s_Unit>().MoveMethod(hit.point.x, hit.point.y, hit.point.z);
To get a component you need to write it like this.
GetComponent<s_Unit>()
in c# then check if you are able to access MoveMethod
+1, I agree this is the preferred way to do it. Just to expand on this slightly, you can also use GetComponent() in the way the original poster specified it, though he'd need speech marks around the 's_Unit' part, like so:
for (int i = 0; i < selectedUnits.Count; i++)
selectedUnits[i].GetComponent("s_Unit").$$anonymous$$ove$$anonymous$$ethod(hit.point.x, hit.point.y, hit.point.z);
The use of AddComponent() in this manner has been deprecated, but GetComponent() can still be used with a string input.
Your answer
Follow this Question
Related Questions
Activating Scripts in another Script? 2 Answers
What to use instead of GameObject.Find and GetComponent 2 Answers
Issue referencing a method that exists in a component that is only decided at runtime 1 Answer
Get Owner Of Bounds On Intersect 1 Answer
Referencing variable from another script on another object 3 Answers