- Home /
I need help with raycasts and with color of gameobject [SOLVED]
So i am creating my second game and I want this game to be finished. I am creating a 3d Game. My player is a stationary object and he is looking at a cube. So the cube is on the ground and the cube is changing colors from red to green. I want to make my player lose if he clicks on the cube while the color of the cube is red. I Have been trying for ages and I can't find a fix to this problem. I'm using raycasts because i think this will be the easiest way but i just can't get the script to work. I hope that is all the information i needed to give. Im open to all suggestions on how to do this without raycasts and with something else. Thanks.
in the "changing colors" , is a simple swap of red to green or is there a blending? If simple swap, ins$$anonymous$$d of swapping colors maybe swap identical cubes? The green cube and red cube alternating ins$$anonymous$$d of colors. Then raycast can get the name of the object and if gets the red cube name he loses
Answer by silvematt · May 22, 2020 at 09:06 PM
Hello. You can do a simple thing like this:
public class CubeStatus : MonoBehaviour
{
public bool isGreen = false;
void SwapColor(bool green)
{
// Change color material
isGreen = green;
}
}
In this way you've saved the state of the cube.
Where you do the Raycast, add a reference for the CubeStatus component:
public class RaycastShooter : MonoBehaviour
{
[SerializeField] CubeStatus status; // Assign it in the inspector
public void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(rayOrigin, forwardVect, out hit, range))
{
if (hit.transform.CompareTag("TheCube"))
{
if (status.isGreen)
// we've hit good
else
// game over
}
}
}
}
Look that in this case the Cube must have the tag "TheCube", otherwise it will not pass the if condition.
Answer by dahiyabunty1 · May 23, 2020 at 11:22 AM
maybe you try
if(hit.gameobject.meshrender.sharedmaterial.color == color.green) { //do stuff }
Script doesn't work. It gives me an error. Error CS1061 'GameObject' does not contain a definition for 'meshrender' and no accessible extension method 'meshrender' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
Answer by C4p3erx · May 23, 2020 at 11:48 AM
Thank you both for your answers here :). @silvematt @dahiyabunty1 Setting booleans is such a obvious thing to do idk why I didn't do it tho:/. I will try both solutions today and I will let you know what works for me. I have a problem with the first script tho. So on the first script when I change the color of the cube won't it stay the same color all the time? Right now Im using coroutines for the color changing on the cube beacuse I want it constantly to be changed not only one time. The second script is good thank you:)