Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

i want to get a component value from the game object which collides with my trigger's object script. this is my code on the trigger:

 void OnTriggerEnter (Collider obj){
     if(obj.GetComponent<motor>().enabled == true){
         passed = true;
     }
 }

and this is the error i get:

NullReferenceException: Object reference not set to an instance of an object
 cp.OnTriggerEnter (UnityEngine.Collider obj) (at Assets/Scripts/cp.cs:15)

also when changing the code on the trigger:

 motor mObj = obj.gameObject.GetComponent();
    if(mObj != null){
         //code here
         Debug.Log("mObj not null");
     }else{
             Debug.Log("mObj is null");
     }

it returns

mObj is null

but the parent obj does have that 'motor' script, other scripts in the car which enter the trigger can access it

share|improve this question
    
<motor> is case sensitive? –  dnk drone.vs.drones Aug 25 at 13:02
    
the script name is all lowercase @dnkdrone.vs.drones –  Bill Bodkin Aug 25 at 13:03
    
try "motor m = obj.GetComponent<motor>();" –  dnk drone.vs.drones Aug 25 at 13:05
    
tred that: 'code' motor mObj = obj.gameObject.GetComponent(); if(mObj != null){ //code here Debug.Log("mObj not null"); }else{ Debug.Log("mObj is null"); } 'code' returned 'code' mObj is null 'code' –  Bill Bodkin Aug 25 at 13:09

2 Answers 2

i found that it must be the wheel collides or some other child causing the issue anyway here is the code i now use

    void OnTriggerEnter (Collider obj){


    motor mObj = obj.transform.parent.gameObject.GetComponent<motor>();
    if(mObj != null){
        //code here
        Debug.Log("mObj not null");
        if(mObj.enabled == true){
            Debug.Log("cp passed");
        passed = true;
        }
    }else{
        Debug.Log("mObj is null");
    }

}

thank you for helping

share|improve this answer
    
No probs :)...... –  Hash Buoy Aug 25 at 16:11

Make the following changes to the code.

    motor mObj = obj.gameObject.GetComponent<motor>(); 
    if(mObj != null){
         //code here
         Debug.Log("mObj not null");
     }else{
             Debug.Log("mObj is null");
     }

On trigger will only work if the game object to which this script is attached have a collider. It won't work if only the children have colliders.

share|improve this answer
    
returns "mObj is null" –  Bill Bodkin Aug 25 at 13:12
    
the object to enter the trigger is a car with only a colder on its body (currently just a cube) and wheel collides, would the wheel collides be the issue? –  Bill Bodkin Aug 25 at 13:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.