- Home /
A Question about GetComponent() (when accessing scripts)....
I have a game where you instantiate troops with waypoints to move to another area.
The troops have a waypoint script attached to them.And I want to access the waypoint script target variable so I can set the waypoint to where I clicked.
I have set up the clicking to find which gameObject I clicked (raycast hit) but how will I set up a way to access the target variable (a Transform) to the clicked target?
By the way, I read the documentation on GetComponent but I don't know how to get the variable and how to set it (is it just like regular once you get the variable?).
Thanks in Advance. (Please attach script to your answer :P)
Note: I want to set the target variable to where I clicked only for that unit so instantiating waypoints won't work because all units will go for that point.
Answer by Loius · Oct 04, 2010 at 05:34 AM
Use
var newTroop : GameObject = Instantiate( troopObject );
newTroop.GetComponent(WayPointScript).target = clickedTransform;
Then newTroop will be set to your newly instantiated troop object.
Answer by Ashkan_gc · Jul 24, 2010 at 04:16 AM
in java script just write
GetComponent(yourScriptName).target=clickedTransform;
in C# you should use one of these two methods:
generics
GetComponent<yourScriptName>().target = clickedTransform;
passing the type of the script to general function
(GetComponent(typeof(yourscriptname)) as yourscriptname).target=clickedTransform;
you can cache the result of GetComponent to use it later. create a variable of type yourscript and in Start use GetComponent to set it to the component's reference and then use that variable instead of calling GetComponent in each click event. it's much faster in devices like the iphone.
var w : WayPointScriptName;
function Awake ()
{
w = GetComponent(WayPointScriptName);
}
now you can just use w.target anywhere you want.
How would I connect this to a newly instantiated prefab (tell the new prefab to have target set)?? I want to do it in a way without using Gameobject.Find. Basically find the most recently instantiated prefab and tell the target to be where I clicked. But I don't want all of the units to be affected, only this one. How would I do this?
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
create GUI.Label and then access to it.. 2 Answers
Problems assigning transforms on another script during Start(). 2 Answers
'thrust' is not a member of UnityEngine.Component 1 Answer
How do I select a joint component from a GameObject that has multiple joint components? 1 Answer