I’ve been working on my runner game and I’m having some difficulty making using of GetComponent. What I want to do is have a script: GameController store an enemy speed variable that every second, I want it raise the global speed of my enemy objects.
My problem is that I’m having trouble figuring out how to use GetComponent to get it to work. Is there a way to access the script: EnemyBehavior directly and change the enemySpeed variable in it? Or do I need to do something else to modify the behavior?
What I did that didn’t work was the following:
public var lSpawnLoc: GameObject;
public var fSpawnLoc: GameObject;
public var startSpeed: float = 0.8;
private var spawnObject1 : SpawnObject;
private var spawnObject2 : SpawnObject;
private var enemyBehavior : EnemyBehavior;
private var newEnemySpeed : float;
function Start ()
{
spawnObject1 = lSpawnLoc.GetComponent(SpawnObject);
spawnObject2 = fSpawnLoc.GetComponent(SpawnObject);
InvokeRepeating("Spawn",3.0,3.0);
enemyBehavior.GetComponent(EnemyBehavior);
InvokeRepeating ("AddSpeed",1.0,1.0);
}
function Spawn()
{
var choice: int = Random.Range(0,2);
if (choice == 0)
{
spawnObject1.CreateEnemy();
}
else
{
spawnObject2.CreateEnemy();
}
}
function AddSpeed()
{
enemyBehavior.enemySpeed = newEnemySpeed;
newEnemySpeed += .01;
}
CVogel
2
Let’s say you have a GameController Script with an ‘enemySpeedIncrease’ variable defined.
GameController → enemySpeedIncrease.
Now, from other scripts in the same scene, you can access this GameController Script as follows. Let’s say you have an Enemy object with an EnemyScript script. In EnemyScript…
EnemyScript (C# example)
using UnityEngine;
using System.Collections;
public class EnemyScript : MonoBehaviour {
public float currentSpeed;
public GameController GMC;
// Use this for initialization
void Start () {
GMC = FindObjectOfType(typeof(GameController)) as GameController;
}
// Update is called once per frame
void Update () {
currentSpeed += GMC.enemySpeedIncrease;
Debug.Log ("Enemy Speed is: " + currentSpeed);
}
}
–
You see you have to give your 2nd script a reference to the first script, and load it with FindObjectOfType or a similar function.
Hopefully this helps!
Chris Vogel