0

I have two 3d buttons in my scene and when I gaze into any of the buttons it will invoke OnPointerEnter callback and saving the object the pointer gazed to.

Upon pressing Fire1 on the Gamepad I apply materials taken from Resources folder. My problem started when I gazed into the second button, and pressing Fire1 button will awkwardly changed both buttons at the same time.

This is the script I attached to both of the buttons

using UnityEngine;
using UnityEngine.EventSystems;
using Vuforia;
using System.Collections;

public class TriggerMethods : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
Material _mat;
GameObject targetObject;
Renderer rend;   
int i = 0;  

// Update is called once per frame
void Update () {
    if (Input.GetButtonDown("Fire1"))
        TukarMat();
}

public void OnPointerEnter(PointerEventData eventData)
{        
    targetObject = ExecuteEvents.GetEventHandler<IPointerEnterHandler>(eventData.pointerEnter);       
}

public void OnPointerExit(PointerEventData eventData)
{
    targetObject = null;
}    

public void TukarMat()
{

    Debug.Log("Value i = " + i);

    if (i == 0)
    {
        ApplyTexture(i);
        i++;
    }
    else if (i == 1)
    {
        ApplyTexture(i);
        i++;
    }
    else if (i == 2)
    {
        ApplyTexture(i);
        i = 0;
    }
}

void ApplyTexture(int i)
{
    rend = targetObject.GetComponent<Renderer>();
    rend.enabled = true;
    switch (i)
    {
        case 0:                
            _mat = Resources.Load("Balut", typeof(Material)) as Material;
            rend.sharedMaterial = _mat;
            break;
        case 1:
            _mat = Resources.Load("Khasiat", typeof(Material)) as Material;
            rend.sharedMaterial = _mat;
            break;
        case 2:
            _mat = Resources.Load("Alma", typeof(Material)) as Material;
            rend.sharedMaterial = _mat;
            break;
        default:
            break;
    }
}

I sensed some logic error and tried making another class to only manage object the pointer gazed to but I was getting more confused.

Hope getting some helps

Thank you

1 Answers1

0

TukarMat() is beeing called on both buttons when you press Fire1. If targetObject is really becoming null this should give an error on first button since it's trying to get component from a null object. Else, it'll change both as you said. Make sure OnPointerExit is beeing called.

Also, it seems you are changing the shared material. The documentation suggests:

Modifying sharedMaterial will change the appearance of all objects using this material, and change material settings that are stored in the project too.

It is not recommended to modify materials returned by sharedMaterial. If you want to modify the material of a renderer use material instead.

So, try changing the material property instead of sharedMaterial since it'll change the material for that object only.

Community
  • 1
  • 1
Luís da Mota
  • 58
  • 3
  • 9