Why doesnt my gameobject get filled?

I am trying to create a select object script in unity.

What it should do is when i hover over an object it colors red (and it does) and when i press “1” the GameObject targetSelected will be filled with the object i am hover on on that moment. In a Debug.Log this all works fine, the targetHighlighted is filled.

When i press “1” however the targetHighlighted object is empty. It doesn’t matter if i press it still on the object or away from it.

Ofcourse the code was more extensive to use it the way i want. But in this code is the problem, so i reduced it to this.

Can anyone help me why when I press “1” the the Debug.Log doesn’t show the targetHighlighted?

Basicly why do the mouseenter and mouseexit log the right Object, and the setTarget function doesnt?

Thanks in advance.

using UnityEngine;
using System.Collections;

public class TargetSelectionScript: MonoBehaviour {
GameObject targetHighlighted;
GameObject targetSelected;
Renderer rend;
Color initialColor = Color.white;
Color selectedColor = Color.red;
public GameControllerScript gameController;

void Start() {

}

void Update() {
    if (Input.GetKeyDown("1")) {
        SetTarget();
    }
}

void OnMouseEnter() {
    SelectTarget();
}

void OnMouseExit() {
    ClearTarget();
}

void SelectTarget() {
        RaycastHit hitInfo = new RaycastHit();
        Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
        targetHighlighted = hitInfo.transform.gameObject;
        rend = targetHighlighted.GetComponent < Renderer > ();
        rend.material.color = selectedColor;
        Debug.Log("Selected target: " + targetHighlighted);
    
}

void ClearTarget() {
    Debug.Log(targetHighlighted);
}

void SetTarget() {
    Debug.Log(targetHighlighted);
}

}

OnMouseEnter() is for the object that you are entering, not the main script.
see here

i would find a better way of selecting targets, maybe put your selectTarget() routine in Update()

@bubzy

Hi, thanks for youre reply. I was under the impression to use OnMouseEnter because it only is triggered once per object enter.

But if its better to use selecting the target via the Update function, I will give it a try tonight. Thanks.

PS: I still am very curious though, why my current code doesnt work :wink: