- Home /
change properties of gameObject
Hi,
Given I can find a single enemy.
q1)will I run into trouble by changing this objects properties here in a script (not attached to it ) after I have accessed the object ? I could now change the position, how it moves, destroy it , disable one of its components etc. Am I getting a copy of this object or a pointer to the object would be how programmer of c++ would ask this question.
q2) to access a list of objects is there another function to use? I might have 10 enemy objects.
private GameObject myenemy;
public class SuperClass : MonoBehaviour // Don't forget to declare a class in C#
{
void Start (){
myenemy = GameObject.Find ("Enemy");
}
// Update is called once per frame
void Update () {
myenemy.transform.position = new Vector3(0, 0, 0);
}
}
myenemy = GameObject.Find("Enemy") would make myenemy a pointer, it is not a duplicate.
You can put a component (script) onto the object and cache the pointer to that too, so then you could do something similiar to..
enemy = GameObject.Find("Enemy").GetComponent(EnemyBehavior) as EnemyBehavior;
And then address it like..
enemy.health = blah;
ok thanks for that. is there a way to get a list of objects like every enemy object?
I personally prefer to instantiate everything in code, so I always explicitly control what's in the scene.. Searching for objects in the hierarchy is a fairly sloppy practice - but it's fine for prototyping.
Answer by jtbentley · Jun 05, 2012 at 03:20 AM
Short answer, that makes the equivalent of a pointer.
To disable components, you can utilise something akin to...
myEnemy = GameObject.Find("Enemy").GetComponent(BehaviorScript);
myEnemy.enabled = false;
This page lists the basics of adding components etc... But this page (Unity Manual) goes into much more detail about components/linking etc.
$$anonymous$$eep in $$anonymous$$d that Find( name ) is the slowest find function. By type or tag is much better. Even then, most of the time they can be avoided by a good design.
I should be using find by tag ins$$anonymous$$d as find is the slowest find function? How do I use code ins$$anonymous$$d of using the find function?
Can declare the var as public to initialize it in the editor, or use a singleton. There probably is other ways, but it's late.
You mean declare the Enemy object as public somewhere somehow? I dont know where you do this?
Why is the find function an issue with performance anyway? If I declare the variable to find something in start () then in update this should be an issue?
Your answer
Follow this Question
Related Questions
Enemy Moves Jitters when Supposed to Be Still 0 Answers
Predict enemy position in X seconds? 1 Answer
Photon Syncing Enemies with Other Clients? 1 Answer
Return Enemy To Start Position 1 Answer
How to Return Enemy to startPosition 1 Answer