- Home /
I am trying to spawn and move a asteroid but the spawnner script doesnot access the script attached to the asteroid.
Spawner Script
public class AsteroidSpawner : MonoBehaviour { [SerializeField] GameObject asteroidPrefab;
Asteroidbody astbody;
private void Awake()
{
astbody = asteroidPrefab.gameObject.GetComponent("Asteroidbody") as Asteroidbody;
}
void Start ()
{
Vector3 pos = new Vector3(0, 0, -Camera.main.transform.position.z);
astbody.Initilise(Direction.Left);
Instantiate<GameObject>(asteroidPrefab, pos, Quaternion.identity);
}
}
Asteroid Body
public class Asteroidbody : MonoBehaviour { CircleCollider2D cc; float radius;
void Start ()
{
cc = GetComponent<CircleCollider2D>();
radius = cc.radius;
}
public void Initilise(Direction dir)
{
float angle = Random.Range(15, 45);
if(dir == Direction.Down)
{
angle = angle + 180;
}
else
{
if(dir==Direction.Left)
{
angle = angle + 90;
}
else if(dir==Direction.Right)
{
angle = angle - 90;
if(angle<0)
{
angle = 360 + angle;
}
}
}
Vector2 direction = new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad));
float magnitude = Random.Range(2, 4);
GetComponent<Rigidbody2D>().AddForce(direction * magnitude, ForceMode2D.Impulse);
}
void OnBecameInvisible()
{
Vector2 position = transform.position;
// check left, right, top, and bottom sides
if (position.x + radius < ScreenUtils.ScreenLeft ||
position.x - radius > ScreenUtils.ScreenRight)
{
position.x *= -1;
}
if (position.y - radius > ScreenUtils.ScreenTop ||
position.y + radius < ScreenUtils.ScreenBottom)
{
position.y *= -1;
}
// move ship
transform.position = position;
}
}
Direction enum public enum Direction { Left, Right, Up, Down
}
Answer by Vega4Life · Dec 11, 2018 at 03:47 PM
You are trying to get the script off the asteroid prefab, you need to get it off the instance. Example:
Vector3 pos = new Vector3(0, 0, -Camera.main.transform.position.z);
GameObject go = Instantiate<GameObject>(asteroidPrefab, pos, Quaternion.identity);
astbody = go.GetComponent<Asteroidbody>(); // This is what you need
astbody.Initilise(Direction.Left);
Remove the one from awake and add the bottom line above to your start
//Like this actually
Vector3 pos = new Vector3(0, 0, -Camera.main.transform.position.z);
GameObject go = Instantiate<GameObject>(asteroidPrefab, pos, Quaternion.identity);
astbody = go.GetComponent<Asteroidbody>();
astbody.Initilise(Direction.Left);
Yep. They should probably put it all in awake as well, but it gets them going. :)
Your answer
Follow this Question
Related Questions
i have a problem with reloading with Time.time 2d game c# Unity 2020.2 1 Answer
What is the purpose of this function? "protected virtual void Init() { }" 1 Answer
I am trying to spawn multiple asteroids but only one of them is screen wrapping. 0 Answers
How to move Instantiated 2D objects by 0.5 using arrows(or mouse) 1 Answer
How would i calculate the size of a 2D area closed off by multiple colliders? 1 Answer