- Home /
Create a bot that eats objects,create a bot who eats things Unity 2D
Hello, so i tried making a bot that eats objects and when he eats them they disappear and he gets bigger, but these objects are spawned by a spawner so when he eats an object he stops moving , so is there a way to make him move again? Here is the code:` public class Bots : MonoBehaviour { public float Speed; public int score = 0; private Transform target; public float Increase;
private void Start()
{
target = GameObject.FindGameObjectWithTag("Food").GetComponent<Transform>();
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target.position, Speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Food")
Destroy(other.gameObject);
transform.localScale += new Vector3(Increase, Increase, Increase);
score++;
Debug.Log(score);
}
}`
Answer by Caeser_21 · Mar 25 at 05:37 PM
Create a new private void(Called "FindFood") and move target = GameObject.FindGameObjectWithTag("Food").GetComponent<Transform>();
from 'Start()' to 'FindFood()', then just call that function form 'Start()' and call it at the end of the 'OnTriggerEnter2D()' code
You code should look like this at the end
private void Start()
{
FindFood();
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target.position, Speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Food")
Destroy(other.gameObject);
transform.localScale += new Vector3(Increase, Increase, Increase);
score++;
Debug.Log(score);
FindFood();
}
private void FindFood()
{
target = GameObject.FindGameObjectWithTag("Food").GetComponent<Transform>();
}
Still doesn't work it says MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
Never mind it worked i putted Find Food function in update() and it worked private void FindFood() { target = GameObject.FindGameObjectWithTag("Food").GetComponent(); }
private void Start()
{
FindFood();
}
void Update()
{
FindFood();
transform.position = Vector2.MoveTowards(transform.position, target.position, Speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Food")
Destroy(other.gameObject);
transform.localScale += new Vector3(Increase, Increase, Increase);
score++;
Debug.Log(score);
FindFood();
}
Your answer
Follow this Question
Related Questions
Create Bot who plays my game 1 Answer
How can I make a bot follow a predefined path? 1 Answer
Scaling and animation movement 1 Answer