- Home /
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]
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?
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--;
}
}
}
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
}
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613065623im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
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