Search Unity

How instantiating GameObject works?

Discussion in 'Scripting' started by 987054win, Apr 20, 2014.

  1. 987054win

    987054win

    Joined:
    Apr 12, 2014
    Posts:
    27
    This is my code for instantiating game object.

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Cube : MonoBehaviour {
    5.  
    6.  
    7.  
    8.     public GameObject Hex;
    9.     private GameObject[] z=new GameObject[10];
    10.     private int Count=0;
    11.     private float plusX=5.0f,plusY=3.0f;
    12.     Vector3 Mov;
    13.        Quaternion Rota=new Quaternion(0.0f,0.0f,0.0f,0.0f);
    14.  
    15.     void Start () {
    16.  
    17.         Mov = new Vector3 (plusX, plusY);
    18.  
    19.     }
    20.    
    21.  
    22.     void Update () {
    23.         if (Input.GetKeyDown (KeyCode.A)) {
    24.            
    25.                     z[Count]=Instantiate (Hex, transform.position + Mov, Rota)as GameObject;
    26.                         Count++;
    27.                        Debug.Log("Count="+Count);
    28.  
    29.                 }
    30.  
    31.            
    32.     }
    33. }
    34. }
    when I run the script I think that in a console when I press 'A' 3 times it'll show,
    but when I run the script and press 'A'
    1st time
    2nd time
    3nd time
    Why is it happening.Anyone who knows the answer plss help, thanks in advance.
     
  2. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    The code you have would work properly, the result should be in the reverse order from what you have

    Code=1
    Code=2
    Code=3

    Are you saying that it is some how cumulating the log? (so your overall log looks like this?

    Code=1
    Code=2
    Code=1
    Code=3
    Code=2
    Code=1

    Because as I read the code it should not do that. It should simply give a response every time the A key is pressed down.
     
  3. wondyr

    wondyr

    Joined:
    Nov 30, 2013
    Posts:
    36
    I Rota in line 25 suppost to be Rotate?
     
  4. 987054win

    987054win

    Joined:
    Apr 12, 2014
    Posts:
    27
    Yes, it is.
     
  5. 987054win

    987054win

    Joined:
    Apr 12, 2014
    Posts:
    27
    Thank you guys.I get it. The problem came from when I add my script to the cube that I wanted to clone so, when I cloned the cube. It's starting to clone itself. Am I right?