I have created three class one for my player one for my enemy and one as a gamecontroller
in player Script i have written the code for its movement and in enemy i have just declared a variable that will give me the current position of the generated enemy.As in gamecontroller we are creating number of enemies at runtime and getting the position of the currently generated enemy and making it translate towards our player.but when i am accessing the current position of the enemy i am getting the nullreference exception.So i am pasting here my code of gamecontroller.
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public GameObject objectToCreate;
//public Vector2 myPosition = Random.insideUnitCircle * 15;
public float timerKInterval = 0.85f;
public float timer = 0.0f;
float minX = -30.0f;
float maxX = 20.0f;
float minZ = -35.0f;
float maxZ = 35.0f;
int direction;
private Player player;
private Enemy enemy;
public Vector3 startPoint;
float duration = 1.0f;
float startTime ;
private Vector3 EnemyPos ;
//Vector3 endPoint = transform.position(-2.650055,2.823138,5.278267);
//Vector3 PlayerPosition = (-2.650055,2.823138,5.278267);
void Start() {
player = GameObject.FindObjectOfType(typeof(Player)) as Player;
enemy = GameObject.FindObjectOfType(typeof(Enemy )) as Enemy;
}
void Update () {
timer += Time.deltaTime;
if(timer >= timerKInterval){
timer = timer - timerKInterval;
createEnemy();
transform.position = Vector3.Lerp(EnemyPos, player.myPosition, (Time.time - startTime) / duration);
Debug.Log("myPosition " +player.myPosition + "EnemyPos " +EnemyPos);
}
}
void createEnemy(){
startTime = Time.time;
//Rigidbody clone;
Quaternion rot = Quaternion.identity;
float randomx = Random.Range(minX, maxX);
float randomz = Random.Range(minZ, maxZ);
float randomy = 4.823138f;
direction = Random.Range(1,5);
//Debug.Log("direction " + direction);
switch(direction) {
case 1:
minX = -30.0f;
maxX = 30.0f;
minZ = 35.0f;
maxZ = 35.0f;
break;
case 2 :
minX = 25.0f;
maxX = 25.0f;
minZ = -35.0f;
maxZ = 35.0f;
break;
case 3:
minX = -30.0f;
maxX = 30.0f;
minZ = -35.0f;
maxZ = -35.0f;
break;
case 4:
minX = -20.0f;
maxX = -20.0f;
minZ = -35.0f;
maxZ = 35.0f;
break;
}
//Vector3 posi = new Vector3((Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius);
Vector3 posi = new Vector3(Player.playerPositionX + randomx, randomy, Player.playerPositionZ + randomz);
///Debug.Log("randomx "+randomx + "randomy "+randomy +"randomz "+randomz );
//Debug.Log("randomx "+randomx);
//Debug.Log("randomx "+randomx);
//if(posi > myPosition){
Instantiate(objectToCreate, posi, rot);
EnemyPos = enemy.EnemyPosition;
//startPoint = transform.position;
//Debug.Log("start point " + startPoint);
//}
}
}