Simple turret placement script gone wrong [unity collision breaks after 1.5 minutes]

TL;DR - I wrote a simple (working) script which breaks for no apparent reason after a certain amount of time.

I’ve written a very simple script which makes a cube follow the mouse. If the cube collides with the terrain, it turns red. If it stops colliding, it turns green.

This is only a rough test and in an actual implementation, the user would be placing a turret. Green meaning it’s a valid place, and red meaning it cannot be built there.

It works perfectly at first but, after roughly 1 minute 25 seconds, it breaks. When colliding it stays green (it should be red) and at a very fast constant rate declares that it is colliding and not colliding over and over again.

Given that the script is so simple, I’m not sure what happens to cause this change in behaviour. Other than the camera, and a light, the cube and terrain are the only objects in the scene.

Some of the code is borrowed from the forums (this is a rough test of an idea) but, I do understand what they’re doing.

So, my initial question is do you have any suggestions why this might be happening?

As a secondary question, do you experience random situations like this? I tend to bump into them with Unity but, it could just be me being a bit silly.

I’ve attached the script.

Any help is appreciated. Have a nice day! :slight_smile:

2953312–219064–FollowMyMouse.cs (1.48 KB)

I’ve just attached a couple of images to show what it does.
Valid building spot (no collision):

Not a valid building spot (colliding):

I see a big problem there, if you collide with 2 collider but exist only one : the color is greend but should be red.

you should do something like : (carefull not tested)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowMyMouse : MonoBehaviour {

    public GameObject objToBuild;
    public List<Collider> colliders = new List<Collider>();
    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {

        Plane plane = new Plane(Vector3.up, 0);
        float dist;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (plane.Raycast(ray, out dist))
        {
            Vector3 point = ray.GetPoint(dist);
            point.y += 8;
            gameObject.transform.position = point;
        }
   
    if(colliders.Any())
{
Color badColour = new Color(1.0f, 0.0f, 0.5f, 1);
        setColour(badColour);
}else
{
Color goodColour = new Color(0.0f, 1.0f, 0.5f, 1);
        setColour(goodColour);
}


       
    }

    void OnTriggerEnter(Collider collider)
    {
        colliders.Add(collider);

        Debug.logger.Log("Hit!");

       
    }

    void OnTriggerExit(Collider collider)
    {
        colliders.Remove(collider);
        Debug.logger.Log("Departing!");

       
    }

    private void setColour(Color colour)
    {
        GameObject whateverGameObject = gameObject;
       

        MeshRenderer gameObjectRenderer = whateverGameObject.GetComponent<MeshRenderer>();

        //Material newMaterial = new Material(Shader.Find("Whatever name of the shader you want to use"));

        //newMaterial.color = whateverColor;
        gameObjectRenderer.material.color = colour;

        //gameObjectRenderer.material = newMaterial;
    }
}

Thank you, CrymX.

I found your implementation interesting as it doesn’t seem as intuitive as just acting on a Unity event (Unity logic, not yours). It did work however, it still suffers the same bug as my initial solution. Unity can be confusing sometimes.

“.Any()” is not a method, so I replaced it with “.Count > 0”. I think this is what you were going for, assessing if there was a collider registered in the list. Do let me know if not.

Thank you for your help. Even though I still have the bug, it was interesting to see an alternative implementation.

To use Any : Enumerable.Any Méthode (System.Linq) | Microsoft Learn

You need the using the LinQ library :

using System.Linq;

.Any do the same thing than Count > 0

When you encounter the bug, can you look at your editor and see what is in the colliders list ?

Just need to keep count of how many you are currently colliding with.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowMyMouse : MonoBehaviour {

    public GameObject objToBuild;

    private int colliderHitCount = 0;
    private Color goodColour = new Color(0.0f, 1.0f, 0.5f, 1);
    private Color badColour = new Color(1.0f, 0.0f, 0.5f, 1);
  
    // Update is called once per frame
    void Update ()
    {
        Plane plane = new Plane(Vector3.up, 0);
        float dist;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (plane.Raycast(ray, out dist))
        {
            Vector3 point = ray.GetPoint(dist);
            point.y += 8;
            gameObject.transform.position = point;
        }
    }

    void OnTriggerEnter(Collider collider)
    {
        setColour(badColour);
        colliderHitCount++;
    }

    void OnTriggerExit(Collider collider)
    {
        colliderHitCount--;

        if (colliderHitCount < 1)
            setColour(goodColour);
    }

    private void setColour(Color colour)
    {
        GameObject whateverGameObject = gameObject;

        MeshRenderer gameObjectRenderer = whateverGameObject.GetComponent<MeshRenderer>();
        //Material newMaterial = new Material(Shader.Find("Whatever name of the shader you want to use"));

        //newMaterial.color = whateverColor;
        gameObjectRenderer.material.color = colour;

        //gameObjectRenderer.material = newMaterial;
    }
}

djfunkey, That is essentially what I ended up doing with my version of CrymX’s solution, just using a list as a method of counting. I tried your suggestion too and that also works but, suffers the same bug.

CrymX, I also tried with the .Any(). Same situation.

However, looking at the colliding objects was a good idea! I printed the contents of the list of colliders. When it is working, it prints “Terrain” into the log however, when it is broken it does not. I’ve indicated the line with an arrow. It stops printing when broken, even when it is colliding.
2953795--219093--TerrainCollision.PNG

Now to see if anything can be discovered from this…

ok, you need to drop the trigger logic. I think that will hurt you in the long run.

Try this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
 
public class FollowMyMouse : MonoBehaviour {
 
    public GameObject objToBuild;
 
    private int colliderHitCount = 0;
    private Color goodColour = new Color(0.0f, 1.0f, 0.5f, 1);
    private Color badColour = new Color(1.0f, 0.0f, 0.5f, 1);
 
    // Update is called once per frame
    void Update ()
    {
        Plane plane = new Plane(Vector3.up, 0);
        float dist;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (plane.Raycast(ray, out dist))
        {
            Vector3 point = ray.GetPoint(dist);
            point.y += 8;
            gameObject.transform.position = point;
			
			var collider = GetComponent<Collider>();
			if(collider != null){
				var bounds = collider.bounds;
				var colliders = Physics.OverlapBox(bounds.center, bounds.extents);
				
				if(colliders.Where(c => c != collider).Any())
				{
					setColour(badColour);
				} else {
					setColour(goodColour);
				}
			}
        }
    }
 
    private void setColour(Color colour)
    {
        GameObject whateverGameObject = gameObject;
 
        MeshRenderer gameObjectRenderer = whateverGameObject.GetComponent<MeshRenderer>();
        //Material newMaterial = new Material(Shader.Find("Whatever name of the shader you want to use"));
 
        //newMaterial.color = whateverColor;
        gameObjectRenderer.material.color = colour;
 
        //gameObjectRenderer.material = newMaterial;
    }
}

bigmisterb, that works perfectly!

I’ve added some comments to represent my understanding of your code after researching a few bits such as => (I’ve previously programmed in Java).

//Get the bounds of the box (kind of like the shape)
                Bounds bounds = collider.bounds;
                //Get all colliders overlapping with this object's collider
                Collider[] colliders = Physics.OverlapBox(bounds.center, bounds.extents);

                //If any of the colliders are not this collider (don't want it hitting itself)
                if (colliders.Where(c => c != collider).Any())

Why do you think trigger logic will hurt me in the long run? Partially because I’m interested and partially because I might have a better understanding of why my code was breaking after a minute and a half.

Thank you very much for your help! (and everybody else who made suggestions).

1 Like

trigger logic says… something entered… something left, it never keeps track of what, if not more than one entered the trigger.

Logic:
object 1, enters the trigger (color is now red)
object 2, enters the trigger (color stays red)
object 1, leaves the trigger (color turns green, even though object 2 is still in the trigger)

Unless you put in object management in the trigger, you will have this problem. By converting this to a “give me everything in this zone” statement, we get around trigger logic all together.

Food for thought:
Since this is a turret defense game. (maybe it is not) you really only want to do the overlap on objects that are turrets or mobs. You could use layering to differentiate between ground, mob and turret.

If this were my game, I would simply use a grid system when placing turrets, and once the turret is placed, find the mean height of the ground given 4 or 9 points where the object is being placed and make the ground level at that point. OR… give each turret a “foot” which will sink into the ground and not have to do that part.

Ah yes, of course, that makes sense. For the testing I only had terrain as another object so we would, of course, have to check to see what objects are involved but, I can see how this could become confusing if not handling it properly.

It’s a little bit of a turret defence game but, with attacking elements as well (you can also deploy a selection of units).
I know of layering but, haven’t previously used it. From what I gather it would be more efficient that checking the objects and their types. I’ll definitely be looking into this. Thanks :slight_smile:

We decided against using a grid based system as we were wanting to use more interesting shaped maps. This just seemed like a simpler solution to us at the time. Well, we originally had certain points on the map (a bunch of cuboid prefabs called “TurretFoundations”) that when hovered over gave an option of which turret to build. It was also decided that method should be replaced, so we thought this would be a nice way to do it.

I’m also planning to have a few invisible zones to ensure players can only build in their portion of the map.