So I want to load different textures for my game object when different conditions are met. There are no errors when I compile this code. The colours change according to the condition, that part does work. The textures do not load though. The textures are stores in a Resources folder in Unity. The first code works but the second does not. Why is this the case? Below is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Level4 : MonoBehaviour
{
Material _mat;
GameObject Sphere;
// Use this for initialization
void Start()
{
Sphere = GameObject.FindWithTag("Player");
//Material _mat = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;
}
// Update is called once per frame
void Update()
{
try
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Renderer _rend = GetComponent<Renderer>();
Material _mat = _rend.material;
_rend.material.mainTexture = Resources.Load("face1") as Texture;
_mat.color = Color.red;
}
}
catch (System.Exception)
{
}
}
}
this is the second code that does not work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class arduino : MonoBehaviour
{
SerialPort sp = new SerialPort("//.////COM6", 9600);// Com port and the baud rate of the arduino
Material m_Material;
GameObject Sphere;
void Awake()
{
Sphere = GameObject.FindWithTag("Player");
m_Material = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;
}
void Start()
{
if (!sp.IsOpen)
{ // If the erial port is not open
sp.Open(); // Open
}
sp.ReadTimeout = 250; // Timeout for reading
}
// Update is called once per frame
void Update()
{
if (sp.IsOpen)
{ // Check to see if the serial port is open
try
{
string portreading = sp.ReadLine(); // get the string output of the serial port
float amount = int.Parse(portreading);
if ((amount > 251f))
{
Renderer _rend = GetComponent<Renderer>();
m_Material = _rend.material;
_rend.material.mainTexture = Resources.Load("face1") as Texture;
m_Material.color = Color.red;
}
}
catch (System.Exception)
{
}
}
}
}