- Home /
reference an object without pre-assigning.
Im at a stump because I have had a problem with functions like GetComponent();.
this is a simple example script for reference:
var myTransform : Transform;
function Update () {
transform.LookAt(myTransform);
}
The script works fine for making my enemies face the player, and all is good. I place the enemy in the scene, attach the script, and set the transform to my player and play it.
What the problem is however, Is I cannot have additional enemies spawn into the scene because The transform will be blank, so the enemy will just shoot at a wall. And having to have every enemy and object on the map have to be pre assigned is tiresome, time consuming and limits thegames capabilities.
What I am wondering, is how to make the first line of the script, or any function looking like this:
var HPtext : GUIText = gameObject.GetComponent(GUIText);
be able to reference an object and target it without having to be pre assigned. How would I go about doing this?
The example you've given is typically not used that way. This example is the classic 'cache of transform' and it is used for the actual gameobject the script is attached to (ie. the "my" in myTransform), not some other transform like the player. While it's not technically wrong, I point it out so you'll better understand other examples that cache the transform.
http://unitygems.com/script-interaction-tutorial-getcomponent-unityscript/
https://unity3d.com/learn/tutorials/modules/beginner/scripting/getcomponent
I learned that the hard way i guess, I just returned to this page because I fixed the problem, but I'll bookmark those pages thanks. :3
Answer by eeveelution8 · Apr 13, 2014 at 01:29 AM
Thanks for the help anyone who responded to this, I fixed the problem.
var Target : Transform;
function FindTarget () : Transform {
if(GameObject.FindWithTag("Player")){
who = GameObject.FindWithTag("Player"); //We have found a Target
}
return who.transform;
}
function Update () {
if(!Target){
Target = FindTarget(); return;
}
transform.LookAt(Target);
}
Answer by nicolasjr · Apr 12, 2014 at 09:03 PM
To find your player with any enemy script, you can simply create a tag and set it on your player, in the inspector.
then, to find your player:
Transform player = GameObject.FindGameObjectWithTag("Player");
Does that solves your problem, Eevee?
Sorry, the code is wrong, it should be:
Transform player = GameObject.FindGameObjectWithTag("Player").transform;
It doesnt work :/
It has a problem with the beginning part being Transform player
shouldnt it be
myTransform = GameObject.FindGameObjectWithTag("Player").transform;
?
Your answer
Follow this Question
Related Questions
Getting script from another script bug 1 Answer
How to access scripts other than by name. 1 Answer
Issues using GetComponent 1 Answer
Changing variables in another script 3 Answers
how to make one script change a variable in another scipt 2 Answers