So I’m making a game for a school project. I have pretty much never coded in my life. What’s wrong with this code? When I run it, the square that I want to change color stays blue rather than changing. Don’t be surprised if this is miserably wrong.
using System.Collections;
using UnityEngine;
public class BlueColor : MonoBehaviour {
bool blue;
bool green;
bool red;
bool yellow;
int counter;
void Start()
{
blue = true;
}
void Update()
{
if (blue == true)
gameObject.GetComponent<Renderer> ().material.color = Color.blue;
if (green == true)
gameObject.GetComponent<Renderer> ().material.color = Color.green;
if (yellow == true)
gameObject.GetComponent<Renderer> ().material.color = Color.yellow;
if (red == true)
gameObject.GetComponent<Renderer> ().material.color = Color.red;
}
void OnCollisionEnter ()
{
if (counter == 0)
{
blue = false;
green = true;
counter = 1;
}
else if (counter == 1)
{
green = false;
yellow = true;
counter = 2;
}
else if (counter == 2)
{
yellow = false;
red = true;
counter = 3;
}
else if (counter == 3)
{
red = false;
blue = true;
counter = 0;
}
}
}
NO need of update there.
You can directly call like
void OnCollisionEnter (collision other)
{
//if you want you can check tag of that gameobject.
counter ++;
print(“counter”+counter);
if (counter == 1)
gameObject.GetComponent ().material.color = Color.blue;
if (counter == 2)
gameObject.GetComponent ().material.color = Color.green;
if (counter == 3)
gameObject.GetComponent ().material.color = Color.yellow;
if (counter == 4)
gameObject.GetComponent ().material.color = Color.red;
}
Note: to work collision your object should have rigidbody. check whether the print is working or not.
@goutham12 , your answer isn’t wrong, but it’s really simple.
If anyone would like to use it, this is a more appropriate way (C#) :
Attach code to sprite with 2D rigidbody and some round sprite. Set colors (Also set alpha! (white/black line under color)
For quick test, set material in Circle 2D collider to bouncy. Enjoy
@Mjllindhorst code edited for 2D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TwoDSwitch : MonoBehaviour {
private int counter = 0;
public List<Color> colors; //list of colors, can be changed in inspector
SpriteRenderer renderReference;
void OnCollisionEnter2D(Collision2D coll){
//if (coll.other.tag == "Wall") { //uncomment to check tag of colliding object
if (counter < colors.Count-1) {
counter++;
} else {
counter = 0;
}
renderReference.color = colors [counter];
//} //uncomment to check tag of colliding object
}
void Start(){
renderReference = GetComponent<SpriteRenderer>();
renderReference.color = colors [counter];
}
}
Setup picture:
@LukasLicek That doesn’t seem to work. that just makes the ball disappear. Also, i should probably mention that this is 2D. Sorry about that.