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
}

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