- Home /
Switching Gameobjects in a variable
I have the following task: I have some cubes, that the player can pick up and move to a slot (a simple plane). The moment the player moves over the slot, the planes should change its color to indicate that it can now be snapped into the slot. That works so far. But if the user decides to move the cube away from the slot, I have to assign the original color to that slot. For that I save the slot in a variable "currentSlot". I reassign the old color (doesn't work) and then I need to erase the currentSlot variable. But I do not know how to do that. As a workaround I assigned it a empty dummy object. But that's not a solution I'm satisfied with. Has anyone a better idea?
Here is my code so far:
function GetSlot() //: GameObject
{
var hit : RaycastHit; //Saves the hitted object
var ray = new Ray(transform.position, (-transform.up)); //check object under the cube
if (Physics.Raycast (ray, hit, 10.0)){
//Debug.Log(hit.collider.gameObject.tag);
if(hit.collider.gameObject.tag =="slot")
{
currentSlot = hit.collider.gameObject;
originalSlotColor = currentSlot.renderer.material.color;
currentSlot.renderer.material.color = activeSlotColor;
}
else
{
currentSlot.renderer.material.color = originalSlotColor;
currentSlot = GameObject.Find("DummyObject");
}
}
Debug.Log(currentSlot);
}
Answer by fschaar · Jul 09, 2012 at 11:52 AM
Hi! Thanks for your answer! the problem was, that the GetSlot function was inside the update function - so it reassigned the color permanently to the original color variable. So the second time it run through, it assigned the new color to the original color variable. After I fixed that by setting the original color in a permanent variable, i recogniced, that, if i move the cube very fast over the slots, sometimes the color stays or more slots change the color at the same time. That's not the goal. So I moved the code to the slot object. now each slot object checks if there is a cube above them and changes color if that is the cause. That works fine. But maybe I get a performance problem later...
Your answer
Follow this Question
Related Questions
How do I change the text of a GUIText object through another GameObject using a variable? 2 Answers
Scripts accessing one another (JS) 0 Answers
How to deactivate something when holding down a key? 1 Answer
GameObject variable change for all of the objects 1 Answer
Set script variable to gameObject 1 Answer