Stop a game object from following an untagged object.
When making game object follow something with tag, but then untagg it while running, why it keeps follow it? even if i instantiate another object that was supposed to follow the previously tagged object, it just keep moving towards it. please how to get an object to stop or just follow another tagged object when the targed is no longer tagged ? thanks
Answer by streeetwalker · Mar 23, 2020 at 05:25 PM
@MounirDev, There is no magical property that tells your object to follow an object with with a tag, or to stop following it if the tag changes. You have to set that in your movement code.
The problem you have is that when you object becomes utagged, your movement code is still doing the same thing. Instead you need it to do something different if the tag changes
One way to do it is for your code to follow this kind of logic:
Keep a referece to the oldTargetObject
Keep a reference to the targetObject
Movement loop begins here {
if I am walking then targetObject tag = what I want
else if I am running targetObject tag = something else
if targetObject tag = what I want
move to targetObject position
else
move to oldTargetObject position
}
Thanks for answering @streeetwalker ! I'm not sure how to switch a target game object when untagg an object, this is the code i'm using :
when the little home is full with one habitant, i untagg it but all the objects just stick to it like this :
I tried using a list of objects but i didn't implement it well..
before you do anything you need code to deter$$anonymous$$e if you are walking or running. Where is that happening?
And, where is that code that does tagging or untagging? How are you doing that?
Not seeing the rest of your code, it seems like you're kind of going the long way around to find a solution to what really is a simple problem.
For one, as a general rule you should not use GameObject.Find - it is slow, and is kind of lazy way of coding. In the long game of learning to code in Unity it is better set up all of your game objects to begin with using either public variable references and drag them to your script inspector, or assign them to variables at the time you instance them. If you do that you don't need to check tags at all, just switch targets when you run or walk.
A better algorithm is:
public GameObject chickenObject; // drag to the inspector
public GameObject dogObject; // drag to the inspector
private GameObject moveTarget
Update {
code to check for walking or running, using keyboard or what?
if walking moveTarget = chickenObject,
else if running moveTarget = dogObject
transform.pos = $$anonymous$$oveFromTo( transform.pos, moveTarget );
}