Reputation: 41
there are 4 objects A B C D (A=cube1, B=Player, C=cover, D=cap1) D is C's child
If the distance(between A,B) is getting closer, then hidden object C is changing to SetActive(true) so I'd like to show object C but it doesn't work.
what sould i have to change?
public class distance : MonoBehaviour
{
public GameObject cube1;
public GameObject Player;
public GameObject cover;
public GameObject cap1;
float cubeDistance;
void Start()
{
cubeDistance = Vector3.Distance(cube1.transform.position, Player.transform.position);
Debug.Log(cubeDistance);
}
// Update is called once per frame
void Update()
{
if (cubeDistance < 30)
{ GameObject.Find("cover").transform.Find("cap1").gameObject.SetActive(true); }
else { GameObject.Find("cover").transform.Find("cap1").gameObject.SetActive(false); }
}
}
Upvotes: 0
Views: 207
Reputation: 401
It is not working because you are checking the distance one time only, in the Start
function. To check the distance between A and B, you need to calculate the distance every frame in Update
first. So you should put the distance code you are using into Update
, before you check if the distance is less than 30.
Upvotes: 0
Reputation: 1548
if (cubeDistance < 30){
cap1.SetActive(true);
}
else {
cap1.SetActive(false);
}
Use the gameobject references to make the object active/inactive in the game.
Note: GameObject.Find is a heavy operation and should not be called in Update as it will effect the performance.
Upvotes: 1