- Home /
how to get this code to work properly c#
i am trying to get a game object to disappear after it gets close to the player.
here is the code i have so far.
any help is welcomed.
thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
public GameObject Enemy;
public GameObject Player;
private float Rush = -0.005f; //rate at which the enemy moves at the player
public enum EnemyState { Nice, Aggresive }
public EnemyState currentState;
public int close = 2;
private void Update()
{
CheckStates();
}
private void CheckStates()
{
if (currentState == EnemyState.Nice)
{
// Inactive
}
if (currentState == EnemyState.Aggresive)
{
Enemy.transform.Translate((Enemy.transform.position - Player.transform.position) * Rush);
Enemy.GetComponent<Renderer>.enabled = false; // ISSUE HERE?
}
}
}
public class EnemyCollider : MonoBehaviour
{
public EnemyScript masterObject;
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
masterObject.currentState = EnemyScript.EnemyState.Aggresive;
}
}
public void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
masterObject.currentState = EnemyScript.EnemyState.Nice;
}
}
}
You need to wrap your renderer enabled section in a distance check, like this. Also, I'd suggest using a Nav$$anonymous$$eshAgent for your enemy if your game is 3D.
if (Vector3.Distance(player.transform.position, enemy.transform.position) <= close)
{
Enemy.GetComponent<Renderer>().enabled = false;
}
Answer by Cornelis-de-Jager · Mar 25, 2018 at 11:33 PM
You have a syntax error:
//Change this:
Enemy.GetComponent<Renderer>.enabled = false;
// To This
Enemy.GetComponent<Renderer> ().enabled = false;
Answer by Arustyred · Mar 25, 2018 at 11:08 PM
Make sure you are getting the right component to disable. You may need: Enemy.GetComponent<MeshRenderer>().enabled = false;
If that still doesn't work, you could set the enemy to a new layer, and then make sure the camera on your player does not render that layer by unchecking it in the Culling Mask section of the Camera component.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Make script affect only one GameObject instead of making all object with this script be affected. 0 Answers
Distribute terrain in zones 3 Answers
What is the best way to instatiate an array of connected GameObjects? 0 Answers
Object reference not set to an instance of an object 2 Answers