OnTrigger function problem

EVERYTIME i use OnCollision or anything that uses triggers, my game glitches. Here are two examples:

1- I have a cube far away from me, and i am using the OnTrigger function so when the player hits it, the screen goes black. When i start the game, i just need to walk a few meters and my screen will be black even if i am still far away from the object.

2- I have a sphere far away from me, and i want to show a log when i hit it. I start the scene, walk a little and bam! The log is displayed and i am far away from the sphere.

Here is an example that i recently made:

#pragma strict

var Img : UI.Image;
private var Secure = false;

function Start() 
{
    Secure = false;
    Img.enabled = false;
}

function OnTriggerEnter (other:Collider) 
    {
        Secure = true;
        Img.enabled = true;
    }


    function OnTriggerExit (other:Collider) 
        {
            Secure = false;
            Img.enabled = false;
        }

I made the “Secure” variable just to test, and it didn’t solved anything. I think i am missing something here. Could anyone help me? I think i am doing something wrong. If everything is fine, please test it in one of your games to see if the same happens.

From the code given, you can remove the Secure variable because it does nothing. One thing I would check is if there is any game object withing the bounds of the collider on the object you have this script on. The way it is now it will register ALL gameobjects that come into contact with it as opposed to the player object which you can fix with dropping:

if(other.gameobject.tag == "Player")
{
    //code goes here
}

or

 if(other.gameobject.name == "PlayerObjectNameHere")
 {
     //code goes here
 }

inside the OnTriggerEnter/OnTriggerExit functions.

Personally I would use the tag because there is far less of a chance of it changing over the course of development, just don’t forget to set the tag of the player object to Player.

Most likely you hit something else and as you don’t do a check for what you hit in your OnTrigger it goes BAM!
Put a Debug.Log(other.gameObject.name); into your OnTrigger and see what you’ve actually hit.