Help with arrays and checking other object's floats
Hey all,
So here's a quick run down of what I'm trying to achieve: the player clicks on a number of objects, which creates an "order" for which their character moves between them (moves to the first object picked, then the second, then the third, etc). Each object that can be clicked on has a "Target Script" attached to them (as well as any other script they need). This all works fine and dandy at the moment, as the objects are able to recognise when they've been targeted/when the player character has reached them, etc. The only problem is getting the player to move between objects. Initially, I had this handled by having separate "node" objects instantiate, which the player would then look for, but this seemed a bit much to me.
So what I want to have happen is the following: -When the player hits "go", their character finds all the targeted objects in the level (They bear the tag "target" and their bool "targeted" is set to true). -The character sees what order these objects have been clicked on in (handled with the NodeTargetNo float). -Using their own "NodesHit" float, the character moves from node to node ("I've hit 2 targets/nodes, so now I go to the 3rd).
With my current method, the character is only targeting the first, and it seems to be by sheer luck he is actually targeting the first anyway. Can anyone shed some light on a smoother way to find all the targets, while ordering them based on their own float? Should I be storing the targets earlier on, or using arrays or something similar to cache them and order them there?
using UnityEngine;
using System.Collections;
public class PlayerMovementScript : MonoBehaviour
{
//Setting up most of the variables
public float speed = 5f;
public float NodesHit = 0f;
public float NodesPlaced = 0f;
public bool InAction = false;
public TargetScript TargetScript;
void Awake ()
{
}
void Update ()
{
if (InAction == false) {
Debug.Log ("Planning!");
}
//The state of the player when he is "In Action"
if (InAction == true) {
if (NodesHit != NodesPlaced) {
GameObject Target = GameObject.FindGameObjectWithTag ("Target");
TargetScript = Target.GetComponent<TargetScript> ();
if (TargetScript.NodeTarget == true) {
if (TargetScript.NodeTargetNo == NodesHit + 1) {
transform.position = Vector2.Lerp (transform.position, Target.transform.position, speed * Time.deltaTime);
}
}
}
if (NodesHit == NodesPlaced) {
return;
}
}
}
//Check for collision with targets and progress to the next one
void OnTriggerEnter2D (Collider2D other)
{
if (InAction == true) {
if (other.gameObject.tag == ("Target")) {
TargetScript = other.GetComponent<TargetScript> ();
if (TargetScript.NodeTarget == true) {
if (TargetScript.NodeTargetNo == NodesHit + 1) {
TargetScript.Triggered = true;
NodesHit += 1f;
}
else {
return;
}
}
}
}
}
}
Thanks for your help!
Your answer
![](https://koobas.hobune.stream/wayback/20220612062803im_/https://answers.unity.com/themes/thub/images/avi.jpg)