I have multiple gameobjects in the scene with different materials on it. When i select a gameobject its material must change to selectMat. My code works in the editor, and on my samsung s8 it also works but after a number of times selecting different gameobjects the selectedMat material stays on the gameobject and it won’t change back to the originalMat.
I realy can use some help with this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class selectobjectNDRD : MonoBehaviour
{
public GameObject selectedObject;
public Material selectMat;
private Material originalMat;
public void Update()
{
if ((Input.GetTouch(0).phase == TouchPhase.Stationary) || (Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(0).deltaPosition.magnitude < 1.2f))
{
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit hit;
{
if (Physics.Raycast(ray, out hit))
{
GameObject hitObject = hit.transform.gameObject;
originalMat = hitObject.GetComponent<Renderer>().material;
SelectObject(hitObject);
hitObject.GetComponent<Renderer>().material = selectMat;
}
else
{
ClearSelection();
}
}
}
void SelectObject(GameObject obj)
{
if (selectedObject != null)
{
if (obj == selectedObject)
return;
ClearSelection();
}
selectedObject = obj;
}
void ClearSelection()
{
if (selectedObject == null)
return;
selectedObject.GetComponent<Renderer>().sharedMaterial = originalMat;
selectedObject = null;
}
}
}
if it’s not a runtime spawn of a material, then asign original mat in the void Start() section; or you could do it in Update() with this: if(originalMaf == null){originalMat == the desired material}
Edit
as an example in your code (untested)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class selectobjectNDRD : MonoBehaviour
{
public GameObject selectedObject;
public Material selectMat;
private Material originalMat;
public void Update()
{
if ((Input.GetTouch(0).phase == TouchPhase.Stationary) || (Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(0).deltaPosition.magnitude < 1.2f))
{
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit hit;
{
if (Physics.Raycast(ray, out hit))
{
GameObject hitObject = hit.transform.gameObject;
if(originalMat == null)
originalMat = hitObject.GetComponent<Renderer>().material;
SelectObject(hitObject);
hitObject.GetComponent<Renderer>().material = selectMat;
}
else
{
ClearSelection();
}
}
}
void SelectObject(GameObject obj)
{
if (selectedObject != null)
{
if (obj == selectedObject)
return;
ClearSelection();
}
selectedObject = obj;
}
void ClearSelection()
{
if (selectedObject == null)
return;
selectedObject.GetComponent<Renderer>().sharedMaterial = originalMat;
originalMat = null;
selectedObject = null;
}
}
}