Hey! I am working on a towerdefence kind of game and I want my towers to be able to detect enemies at a certain range. It is working fine untill I build one more tower. The second tower just won’t shoot while the first tower is going on like normal.
Here is my code:
private var target;
private var posTarget : Vector3;
public var projectile : Rigidbody;
private var cloneProjectile;
public var projectileSpeed : float = 900;
public var skottEld : GameObject;
private var cloneSkottEld;
private var center : Vector3;
private var nextShot = 0.0;
var reloadTime = 0.5;
function Update () { //ändra så att det är function Update() ist
if(Time.time > nextShot && target != null){
nextShot = Time.time + reloadTime;
//target = GameObject.FindGameObjectWithTag("Enemy");
posTarget = Vector3(target.transform.position.x,target.transform.position.y,target.transform.position.z);
this.transform.LookAt(posTarget);
cloneProjectile = Instantiate(projectile, transform.position, transform.rotation);
Destroy(cloneProjectile.gameObject, 6);
cloneProjectile.rigidbody.AddForce(cloneProjectile.transform.forward * projectileSpeed);
//cloneSkottEld = Instantiate(skottEld, transform.position, transform.rotation);
//Destroy(cloneSkottEld, 3);
}
}
function OnTriggerStay(hitTarget : Collider){
if(hitTarget.gameObject.tag == "Enemy" && target == null){
target = hitTarget.gameObject;
}
}
I would really appreciate some help! Thanks in advance ![]()
It seems to work when I put out the towers before I start the game but when I instantiate my second tower it just won't work. Please help! I can't find a sollution!
– FetdressingSo I take it your tower game object has a sphere collider component? And you're letting these colliders trigger OnTriggerStay() instead of manually calling SphereCast? How are you building the second tower? Cloning/instantiating a prefab? Or building it at design time? Is the second tower's layer the same as the first tower's? Does the collider have the right radius?
– TonyLiHey, thanks for the reply! Do you think spherecast would be better? I tried it before but couldn't get it right. It does atm have a 30 radius spherecollider set on trigger. I am just cloning a prefab and then instantiating it. The layer is atm set to ignore raycast at the tower so it won't be in the way for my mouseclick thingy where I build the towers.
– FetdressingI noticed something really weird aswell when I ran it this time, the spherecollider seems to be changing position everytime it fires. And now that I don't have it on maximize at play the second tower starts shooting aswell :OO What has gone so wrong? :P
– FetdressingI think your current approach is preferable to SphereCast. That's some strange behaviour. The Scene View is definitely going to be helpful, since you can see the objects' gizmos. As you're playing, pause the game and check everything on the second tower: Are the layer and collider still correct? Maybe they're getting set wrong somehow.
– TonyLi