How to assign a gameobject to a script that is added dynamically?
I have this script that after a certain event adds a script to a gameobject. This script needs a target(gameobject). Here are the scripts:
Script that adds EnemyAI to gameobject
using UnityEngine;
using System.Collections;
public class AddingScriptsToSelf : MonoBehaviour {
public GameObject mirror;
private MirrorHealth mirrorHealth;
void Awake () {
mirrorHealth = mirror.GetComponent();
}
void Update () {
if(mirrorHealth == null){
gameObject.AddComponent("EnemyAI");
Destroy(this);
}
}
}
EnemyAI:
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxDistance;
private Transform myTransform;
void Awake() {
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxDistance = 2;
}
// Update is called once per frame
void Update () {
Debug.DrawLine (target.position, myTransform.position, Color.green);
//Look at target
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
//move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
EnemyAI tutorial: https://www.youtube.com/watch?v=O8-oZfi4utY
↧