- Home /
 
 
               Question by 
               HowdyMedia · Sep 21, 2014 at 07:37 AM · 
                prefabclasseswrapper  
              
 
              Wrapping Instantiate PreFab in Non-Component Classes
How do you create an object which can be accessed in any component, that also can perform Instantiate to spawn prefabs?
For instance, I want to create an object of Asteroids, in which the CreateAsteroids assigns values to each asteroid object and stores details about the asteroid.
 public class Asteroid : ScriptableObject {
 
     public float xScale;
     public float yScale;
     public float zScale;
     public float health;
     public bool split;
     public GameObject asteroid;
     public string namey;
 
     public void CreateAsteriod(GameObject astObj) {
         xScale = Random.Range(-0.5f,1.5f);
         zScale = Random.Range(-0.5f,1.5f);
         GameObject astObj = Instantiate(asteroid, new Vector3(Random.Range(-4.5f,4.5f),0.0f,13.0f), Quaternion.identity) as GameObject;
         astObj.transform.localScale += new Vector3(xScale,0,zScale);
         Debug.Log ("asteroid_" + GetInstanceID());
         namey = "asteroid_" + GetInstanceID();
         astObj.name = namey;
     }
 }
 
               I can do these sort of things in Java, but can not figure out how to do it within Unity.
               Comment
              
 
               
              I figured it out:
 using UnityEngine;
 using System.Collections;
 
 public class $$anonymous$$ainGame : $$anonymous$$onoBehaviour {
 
     public GameObject asteroid;
 
     void Start () {
     
     }
     
     void Update() {
         if (Random.Range (0.0f, 100.0f) < 3.0f) {
             Asteroid ast = new Asteroid();
             ast.CreateAst(asteroid);
         }
     }
 }
 
 public class Asteroid {
 
     public float xScale;
     public float yScale;
     public float zScale;
     public bool split;
     public GameObject asteroid;
     public string namey;
     public static int instanceID;
 
     public void CreateAst(GameObject asteroid) {
         instanceID++;
         xScale = Random.Range(-0.5f,1.5f);
         zScale = Random.Range(-0.5f,1.5f);
 
         GameObject astObj = $$anonymous$$ainGame.Instantiate(asteroid, new Vector3(Random.Range(-4.5f,4.5f),0.0f,13.0f), Quaternion.identity) as GameObject;
         astObj.transform.localScale += new Vector3(xScale,0,zScale);
         namey = "asteroid_" + instanceID;
         astObj.name = namey;
     }
 }
                 Your answer
 
             Follow this Question
Related Questions
saving to prefab with classes from other scritps 1 Answer
Create models objects and get informations from them 1 Answer
Classes VS Variable Scripts 1 Answer
Creating new instances of classes 2 Answers
Instantiate, Prefabs, Classes 1 Answer