Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Telmach · Mar 28, 2012 at 06:28 AM · instantiatemultipleclone

Why are multiple objects being instantiated when I use clone, but not regular instantiation?

For whatever reason the line 'clone = (BaseGameObject)Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);' always spawns multiple objects, while this line only spawns one everytime 'Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);'.

If it helps, during runtime I get the error 'InvalidCastExcept: Cannot cast from source type to destination type.' on this line;

clone = (BaseGameObject)Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);


 public class ObjectSpawnPoint : BaseGameObject
 {
     void Update()
     {
         if( ... ){
             BaseGameObject clone;
             // Spawn multiple objs
             clone = (BaseGameObject)Instantiate(objectToSpawn, 
                                            spawnerLocation, Quaternion.identity);
            // Spawn only one obj
            //Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);
         }
     }
 
 }

The BaseObjectClass is here

 public class BaseGameObject : MonoBehaviour { /*[...]*/ }

[Edit by Berenger : Removed all the unnecessary code. Full text in comments]

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image GC1983 · Mar 28, 2012 at 06:55 AM 0
Share

Would the clone.addObserver(this); have anything to do with it? When you are using clone variable, you are referencing BaseGameObject's addObserver() which is calling an array. Is this connecting the array to the object causing it to instantiate multiples?

avatar image Berenger · Mar 28, 2012 at 07:09 AM 0
Share

For whatever reason the line 'clone = (BaseGameObject)Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);' always spawns multiple objects, while this line only spawns one everytime 'Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);'.

If it helps, during runtime I get the error 'InvalidCastExcept: Cannot cast from source type to destination type.' on this line;

clone = (BaseGameObject)Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);

using UnityEngine; using System.Collections;

public class ObjectSpawnPoint : BaseGameObject { #region Fields public GameObject objectToSpawn; public bool isActive; public float spawnDelay; public bool spawnImeadiatley;

 public int spawnLimit = 10; //Limits the spawner to only have this many active objects spawned at a time.
 public int onlySpawn = -1; //The spawner will spawn a maximun of this many objects before permanantly shutting down. -1 means it spawns an infinite number of objects
 private int totalSpawned; //The total number of objects spawned by the spawner since its awake meathod has been called.
 private int currentSpawnTotal; //The number of objects spawned by the spawner that are still active.

 private float spawnDelayTimer;
 private Vector3 spawnerLocation;
 private bool justSpawned;

 #endregion

 void Awake()
 {
     renderer.material.color = Color.yellow;
     spawnDelayTimer = Time.time;
     spawnerLocation = transform.position;
     currentSpawnTotal = 0;
     totalSpawned = 0;
     if (spawnImeadiatley)
     {
         justSpawned = false;
     }
     else
     {
         justSpawned = true;
     }

     
 }

 void Update()
 {
     if (isActive)
     {
         if ((onlySpawn == -1 || totalSpawned < onlySpawn) && currentSpawnTotal < spawnLimit)
         {
                 spawnDelayTimer = $$anonymous$$athf.Floor(Time.time % 10.0f);
                 if (spawnDelayTimer == 0f && !justSpawned)
                 {
                     BaseGameObject clone;
                     clone = (BaseGameObject)Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);
                     //Instantiate(objectToSpawn, spawnerLocation, Quaternion.identity);

                     clone.addObserver(this);

                     currentSpawnTotal++;
                     totalSpawned++;
                     justSpawned = true;
                 }
                 else if (justSpawned && spawnDelayTimer != 0f)
                 {
                     justSpawned = false;
                 }
         }
         else
         {
             setActive(false);
         }
     }
 }

 bool getActive()
 {
     return isActive;
 }

 void setActive(bool active)
 {
     isActive = active;
 }

 public override void getNotified(string change$$anonymous$$ade)
 {
     if (change$$anonymous$$ade == "Death")
     {
         currentSpawnTotal--;
     }

     if (change$$anonymous$$ade == "Active")
     {
         currentSpawnTotal++;
     }

     if (change$$anonymous$$ade == "Inactive")
     {
         currentSpawnTotal--;
     }
 }

}

avatar image Berenger · Mar 28, 2012 at 07:10 AM 0
Share

The BaseObjectClass is here public class BaseGameObject : $$anonymous$$onoBehaviour {

 #region Fields
 private PackedSprite spriteAnimation;
 private ArrayList observerArrayList = new ArrayList();
 private int totalObservers = 0;

 #endregion
 
 #region Properties
 
 /// <summary>
 /// Read only Access to the Animated Sprite
 /// </summary>
 public PackedSprite SpriteAnimation
 {
     get 
     { 
         //lazy initialization of spriteAnimation
         if(spriteAnimation == null)
             spriteAnimation = GetComponent<PackedSprite>();
         
         return spriteAnimation; 
     }    
 }
 
 /// <summary>
 /// True if the game is paused.
 /// </summary>
 public bool IsGamePaused
 {
     get { return Time.timeScale == 0; }     
 }
 
 /// <summary>
 /// True if the game object is currently disabled from drawing
 /// </summary>
 public bool IsHidden
 {
     get { return SpriteAnimation.IsHidden(); }    
 }
 #endregion
 
 #region Uinity $$anonymous$$ethods
 
 // Use this for initialization
 protected virtual void Start () {
 
 }
 
 #endregion
 
 #region Custom $$anonymous$$ethods
 
 /// <summary>
 /// Removes the game object and tells the Sprite $$anonymous$$anager to remove the AnimatedSprite from the scene
 /// </summary>
 public void DestroyGameObject()
 {
     notifyObservers("Death");
     SpriteAnimation.Delete();
     Destroy(gameObject);
 }
 
 /// <summary>
 /// Puts the sprite in a hidden state so that it is not visible and disables all colliders attached
 /// </summary>
 public virtual void Hide()
 {
     SpriteAnimation.Hide(true);
     this.enabled = false;
     foreach(Collider c in GetComponents<Collider>())
         c.enabled = false;
 }
 
 /// <summary>
 /// Puts the sprite in a visible state and enables all colliders attached to it
 /// </summary>
 public virtual void Show()
 {
     SpriteAnimation.Hide(false);
     this.enabled = true;
     foreach(Collider c in GetComponents<Collider>())
         c.enabled = true;
 }
 
 public bool IsPlayingAnimtion(string animName)
 {
     return !(SpriteAnimation.GetCurAnim() == null || SpriteAnimation.GetCurAnim().name != animName);    
 }
 
 public void addObserver(BaseGameObject Observer)
 {
     observerArrayList[totalObservers] = Observer;
     totalObservers++;
 }
 
 public void notifyObservers(string change$$anonymous$$ade)
 {
     for (int i = 0; i < totalObservers; i++)
     {
         ((BaseGameObject)observerArrayList[i]).getNotified(change$$anonymous$$ade);
     }
 }
 
 public virtual void getNotified(string change$$anonymous$$ade)
 {
     //ToDo child classes need to define their own responses.
 }

 #endregion

}

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Berenger · Mar 28, 2012 at 07:13 AM

You can't cast Object into a component. You need, first, to cast it into a GameObject with as, and then access the component with GetComponent. I think that's where you're error comes from, and I edited the question accordingly. If it is not, well, sorry :) but the full code is not lost anyway.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to add multiple clones of an object to a list ? Currently only 1 clone gets added. 1 Answer

Why does instantiation of clone cause duplicates 1 Answer

Cloning Problem Script 0 Answers

Instantiate 3 guiTextures at the same 1 Answer

How can I get the x position for the left(and right) of the screen? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges