Trying to make an object "Flee" from the player but it won't work?

I tried this code out and it doesn’t work, an error pops up saying “Object reference is not set to an instance of an object (target)”
my code (C#):

using UnityEngine;
using System.Collections;

public class Flee : MonoBehaviour {
   public int moveSpeed = 10;
   new Vector3 dir;
   GameObject target;
   void Start(){
   target = GameObject.FindGameObjectWithTag("Player");
   }
   void Update(){
	   dir = transform.position - target.transform.position;
	   transform.Translate(dir * moveSpeed * Time.deltaTime);
   }
}

Hi

It’s a bit hard to diagnose from just that code, but if it was me the first thing I would try is moving your ‘FindGameObjectWithTag’ line to inside the update function, and then checking it is valid each frame

void Update()
{
	target = GameObject.FindGameObjectWithTag("Player");
	Debug.Log(target);
	if(target != null)
	{
		dir = transform.position - target.transform.position;
		transform.Translate(dir * moveSpeed * Time.deltaTime);
	}
}

This is definitely not the best way to do things, as that search will be slow. However I suggest it to validate the fact that you are finding the correct game object. If you are indeed detecting it correctly in start, that would suggest the object you found was being destroyed. If so, you’ll need to work out why, and either make it find the correct object, notify the script when the object changes, or just do the search every frame the dodgy way!

-Chris

are you sure you have set the tag?

All I have to do is make the objects be prefabs and then instantiated for some reason