- Home /
Question by
Rizelyn · Jul 04, 2018 at 03:21 PM ·
instantiateparent
Instantiated object not receiving value from parent class
Hey,
I'm trying to make an instantiated object "enemy" move with the speed "moverEnemySpeed" set in the parent class. I don't get any errors indicating the child script can't find moverEnemySpeed, but when I Debug.Log it's value it says "0". In the parent script I set the value to 5...
Anyone know what I'm missing?
Parent class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnerController : MonoBehaviour
{
//The Spawner game object manages the instantiation of the enemies
// Array of GameObject prefabs set in the Engine/Inspector
public GameObject[] mode;
// Spawntime settings
public int spawnInterval;
public float startWait;
public float moverEnemySpeed;
// Runs on start-up game
void Start ()
{
moverEnemySpeed = 5f;
//Repeats a function on declared start-up time startWait and with set interval spawnInterval
InvokeRepeating("Spawn",startWait, spawnInterval);
}
//Spawns the enemies
void Spawn ()
{
//Randomises a spawnposition along the x-axis
Vector3 position = new Vector3(Random.Range(-3.0f,3.0f), 0, 8.0f);
//By default the enemy planes are standing upright and invisible for the top down camera, rotating them 90 degrees on creation fixes that
Quaternion spawnRotation = Quaternion.Euler(90,0,0);
//Picks a random enemy from the array and instantiates it in the game
(Instantiate(mode[Random.Range (0,mode.GetLength (0))],position, spawnRotation) as GameObject).transform.parent = this.transform;
}
}
Child class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : SpawnerController
{
//This script is applied to all instantiated enemy player to make them move downward the screen
//Rigidbodies are needed to move the enemy
private Rigidbody rb;
// Runs on startup game
void Start ()
{
rb = GetComponent<Rigidbody>(); //Gets the Rigidbody component
rb.velocity = -transform.up * moverEnemySpeed; //Starts movement of enemies
Debug.Log(moverEnemySpeed);
}
}
Comment
Best Answer
Answer by tormentoarmagedoom · Jul 04, 2018 at 04:49 PM
Good day.
I dont see where you declare the mover enemy speed in the child script. How it knows what value needs to read?
You should try this :
rb.velocity = transform.down * (transform.parent.GetComponent<SpawnerController>().moverEnemySpeed);
So it will use directly the value in the parents script.
Byee!