- Home /
Random.range Selects the same target? (all turrets choose same target???) (Taget is not selected at random?))
hey gang, just wondering why every turret in my scene with the same gun script targets the same object, when its using random.Range So each turret sound be selecting a random object in array?
for some reason every turret targets the same same "TeamOne" or ""TeamTwo" object and its alwys the first object in the array every time I run the game?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class antiFighterGuns : MonoBehaviour
{
public GameObject[] TargetTs;
public GameObject TargetT;
int index;
public float GunRange = 1200;
public float nextFire;
public float fireRate = 0.5f;
public GameObject LaserObj;
float Distance;
public bool AllyGun;
// Update is called once per frame
void Update()
{
if (TargetT == null)
{
if (AllyGun == true)
{
TargetTs = GameObject.FindGameObjectsWithTag("TeamTwo");
index = Random.Range(0, TargetTs.Length);
TargetT = TargetTs[index];
}
if (AllyGun == false)
{
TargetTs = GameObject.FindGameObjectsWithTag("TeamOne");
index = Random.Range(0, TargetTs.Length);
TargetT = TargetTs[index];
}
}
if (TargetT != null)
{
transform.LookAt(TargetT.transform);
Distance = Vector3.Distance(TargetT.transform.position, transform.position);
}
if (Distance > GunRange)
{
TargetT = null;
}
if (Time.time > nextFire && TargetT != null)
{
nextFire = Time.time + fireRate;
Instantiate(LaserObj, transform.position, transform.rotation);
}
}
}
TargetTs = GameObject.FindGameObjectsWithTag("TeamTwo");
index = Random.Range(0, TargetTs.Length);
This code is correct and doing what you expect it to. So I would guess that somehow the units are not tagged correctly.
Try and put in a - Debug.Log(index);
- and see what number it makes. $$anonymous$$y guess would be that it is 0. $$anonymous$$eaning that it only adds the first unit to the list.
Answer by sisse008 · Sep 16, 2019 at 12:46 PM
your code works fine. check for human errors.
index = Random.Range(0, TargetTs.Length);
Debug.Log("me: " + gameObject.name + " index = " + index);
I would add TargetTs.Length to that logging (maybe it's only finding one - that'd explain why it always randomises to the same index)
Your answer
Follow this Question
Related Questions
Project Scripting - Tracking variables (General Question) 2 Answers
How Do You Parent an Object With Scripts? 1 Answer
What does the word for mean in javascript? 1 Answer
Why button is not display the window 2 Answers
Game is Paused Menu shows up 0 Answers