Constantly Targeting with an InvokeRepeating and Random Targeting
Hi, I have a script which in theory is fine, but there are lots of things that don't work to plan (not syntax errors, the script is fine). It is in C#. The main issue is that I want my object to target the target and follow it for 5 seconds until it resets, but it constantly follows the player, does anybody have any ideas why it would do this and how to stop it? The 2nd issue is that tr_player (the transform variable) always sets itself to my 5th target, so if anyone has any ideas about that it would be very helpful. This is my script:
public Transform Bird;
public Transform tr_Player;
public float f_MoveSpeed = 25.0f, f_RotSpeed = 1000.0f;
void Start () {
tr_Player = GameObject.FindGameObjectWithTag ("Target").transform;
InvokeRepeating("Reset",5, 5);
}
void Update () {
transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
}
void Reset()
{
transform.position = Bird.position;
tr_Player = GameObject.FindGameObjectWithTag ("Target").transform;
transform.LookAt(tr_Player);
}
}
Probably just a noob error but if anyone could help me with those two errors it would be really helpful!
For the second issue you mentioned your code : tr_Player = GameObject.FindGameObjectWithTag ("Target").transform; will go thorugh all objects and find the first one with the tag "Target", and it seems you have more than one. rather use:
GameObject[] targets = GameObject.FindGameObjectsWithTag ("Target");
tr_Player = targets[0]..transform;
Thanks @vintar but that doesn't work, the double stop comes up as an error and when I remove it it comes up with pretty much everything else in red, any other ideas or am I doing something wrong?
The line with the double full stops should be;
Int index = Random.Range(0, targets.Length); //If wanting a random target.
tr_Player = targets[index].GetComponent();
Your answer
Follow this Question
Related Questions
Null Reference Exception for target in a script on a newly instantiated object 0 Answers
How do I solve my Match 3 Game coding error?, 0 Answers
Setting the parent of an instantiated prefab error 1 Answer
How do you convert UnityEngine.GameObject to UnityEngine.Transform? 0 Answers
How do I find a player for AI to target when spawning a player in? 0 Answers