• 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 aditya · Dec 02, 2015 at 08:58 AM · unity 5instantiation

Instantiating wierd problem

i m working on a game where i need to instantiate three random platforms in three columns, but the problem is that sometime the code works properly but sometimes 1 to 2 of my platforms spawning in center of screen ... below is my code

     public GameObject[] platforms;
 
     public GameObject playerObject;
 
     public uint blockCount;
 
     private Vector3 spawnPos;
 
     private GameObject[] lastObjects;
 
     private string goName;
     private uint nameInt;
     private uint j;
 
     private Vector3 lastVec;
     private Vector3 worldPosVec;
 
     void Start(){
         blockCount = 0;
         lastObjects = new GameObject[]{platforms[0], platforms[1], platforms[2]};
         spawnPos = new Vector3 (0f,-7f,0f);
         lastVec = new Vector3 (0f,0f,0f);
         worldPosVec = new Vector3((10f / 100f) * Screen.width,(90f / 100f) * Screen.height, Camera.main.farClipPlane);
         lastVec = Camera.main.ScreenToWorldPoint (new Vector3(0f, -600f, Camera.main.farClipPlane));
         goName = "init";
         nameInt = 1;
         j = 1;
         spawnPos = Camera.main.ScreenToWorldPoint (worldPosVec);
         spawnLeftLine ();
         Instantiate (playerObject, Camera.main.ScreenToWorldPoint(new Vector3((10f / 100f) * Screen.width, (20f / 100f) * Screen.height, Camera.main.farClipPlane)), Quaternion.identity);
     }
 
     void spawnLeftLine(){
         if (blockCount == 0) {
             for(uint i = 0; i < 3; i++){
                 j =(uint) Random.Range(0f,3f);
                 switch(i){
                 case 0:
                     lastObjects[i] = (GameObject)Instantiate(platforms[j], spawnPos, Quaternion.identity) as GameObject;
                     goName = "blockLeft";
                     nameInt = 1;
                     lastObjects[i].gameObject.name = goName.ToString() + nameInt.ToString();
                     break;
                 case 1:
                     worldPosVec.x = (50f / 100f) * Screen.width;
                     worldPosVec.y = (10f / 100f) * Screen.height;
                     spawnPos = Camera.main.ScreenToWorldPoint(worldPosVec);
                     lastObjects[i] = (GameObject)Instantiate(platforms[j], spawnPos, Quaternion.identity) as GameObject;
                     goName = "blockMid";
                     nameInt = 1;
                     lastObjects[i].gameObject.name = goName.ToString() + nameInt.ToString();
                     break;
                 case 2:
                     worldPosVec.x = (90f / 100f) * Screen.width;
                     worldPosVec.y = (90f / 100f) * Screen.height;
                     spawnPos = Camera.main.ScreenToWorldPoint(worldPosVec);
                     lastObjects[i] = (GameObject)Instantiate(platforms[j], spawnPos, Quaternion.identity) as GameObject;
                     goName = "blockRight";
                     nameInt = 1;
                     lastObjects[i].gameObject.name = goName.ToString() + nameInt.ToString();
                     break;
                 }
             }
             blockCount = 3;
         }
     }

the platforms are setup in such a manner that it has a parent Gameobject with spriteRender component on it and nothing else, a child gameObject with a collider on it and nothing else and another child gameObject with Trigger Collider on it and nothing else

Comment
Add comment
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

4 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by wibble82 · Dec 03, 2015 at 02:09 PM

Hi aditya

I've gone over your code and can not instantly see any problems with it, assuming the code you've shown is the only code that spawns platforms. I'm guessing that you are expecting spawnLeftLine to only ever do something once, as it only spawns platforms if blockCount is 0, and you set it to 3 as soon as you've spawned some. As the guys in the previous answer suggest, you approach isn't the tidiest, but doesn't appear to be broken, and if you've verified the spawn positions are correct with debug prints then we have to assume its something else.

Given there's nothing obviously wrong with the code (though I could certainly offer some constructive criticism as to how to write some of it a little better - let me know if you'd like that), my guess is that it could be something to do with your platform prefabs. Could I suggest trying restricting it to only ever spawn platform 0, then try restricting it to only ever spawn platform 1 etc. Perhaps one of those platforms is causing issues, and this will help identify which one.

FYI, I'm currently going on the assumption that you have no other code that might set the position of platforms or spawn platforms. If that's incorrect, we'd need to verify your other code to identify if the problem is elsewhere.

-Chris

Comment
Add comment · Show 4 · 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
avatar image aditya · Dec 04, 2015 at 06:46 AM 0
Share

yes sir obviously i would like to have some suggestion how to make this better and you just make me realize one of my mistake as i m using a script that is moving the spawned platforms up and down, and below is that script ...

     public bool moveDown;
 
     private setSpeed ss;
     private Vector2 newPos;
 
     void Start(){
         ss = GameObject.FindGameObjectWithTag ("GameController").GetComponent<setSpeed> ();
         newPos = new Vector2 (0f,0f);
         newPos.y = ss.speed;
     }
 
     void FixedUpdate(){
         if (moveDown) {
             transform.GetComponent<Rigidbody2D> ().$$anonymous$$ovePosition (transform.GetComponent<Rigidbody2D> ().position - newPos);
             if(transform.position.y < -9f)
                 destroyPlat();
         } else {
             transform.GetComponent<Rigidbody2D> ().$$anonymous$$ovePosition (transform.GetComponent<Rigidbody2D> ().position + newPos);
             if(transform.position.y > 9f)
                 destroyPlat();
         }
     }
 
     void destroyPlat(){
         GameObject.FindGameObjectWithTag ("GameController").GetComponent<instantiatePlatForm> ().blockCount -= 1;
         Destroy(transform.gameObject);
     }



the script that is spawning these platforms is actually making the moveDown variable true or false too after spawning

avatar image aditya · Dec 08, 2015 at 08:07 AM 0
Share

Thanks for bringing my $$anonymous$$d towards the platform object as i accidentally turned the X constrain on and now it is working all fine

avatar image wibble82 · Dec 08, 2015 at 10:29 AM 0
Share

I had a bit of a go at some cleanup. Sorry if its a little broken - I didn't have anything to test it with. Even if you don't use it, I'd take a look - there's a few slight changes that will just help you write neater code in future. And neater code is really good, as it breaks less and is easier to fix!

      public GameObject[] platformPrefabs;
      public GameObject playerPrefab;
      private GameObject[] lastObjects;
   
      void Start(){
          spawnLeftLine ();
          Instantiate (playerPrefab, calculateWorldPos(0.1f,0.2f), Quaternion.identity);
      }
 
      Vector3 calculateWorldPos(float x, float y)
      {
          new Vector3(x * Screen.width,y * Screen.height, Camera.main.farClipPlane);
      }
  
      void spawnLeftLine(){
          lastObjects = new GameObject[3];
         for(uint i = 0; i < 3; i++)
         {
             int playform_idx = Random.Range(0f,3f);
 
             float spawn_x=0;
             float spawn_y=0;
             string spawn_name="";
 
             switch(i)
             {
             case 0:
                 spawn_name = "blockLeft";
                 spawn_x = 0.1f;
                 spawn_y = 0.9f;
                 break;
             case 1:
                 spawn_name = "block$$anonymous$$id";
                 spawn_x = 0.5f;
                 spawn_y = 0.1f;
                 break;
             case 2:
                 spawn_name = "blockRight";
                 spawn_x = 0.9f;
                 spawn_y = 0.9f;
                 break;
             }
 
             GameObject spawn_object = (GameObject)Instantiate(platforms[playform_idx], calculateWorldPos(spawn_x,spawn_y), Quaternion.identity);
             spawn_object.name = spawn_name + "1";
             lastObjects[i] = spawn_object;
         }
      }

The main changes are:

  • removed the use of 'blockCount' as it doesn't do anything - you only call spawnLeftLine once anyway

  • removed the extra 'as GameObject' dynamic casts - you already cast them to GameObject using the static cast '(GameObject)'

  • made lots of member variables local variables

  • made a bit of na$$anonymous$$g more clear

  • $$anonymous$$imized duplicated logic in the switch statement

  • moved the world pos calculation into function, as its used in lots of places

  • renamed arrays that refer to prefabs so they're more clear

  • removed 'nameInt' altogether as it was always 1

In general though, the key guidelines would be to

  • name things clearly

  • avoid duplicating logic where possible - that's a recipe for bugs

  • $$anonymous$$imize 'redundant state' - i.e. storing data in member variables when you don't need to

-Chris

avatar image aditya wibble82 · Dec 08, 2015 at 12:56 PM 0
Share

thanks chris for taking your precious time to write this code for me, but there is a slight problem with this code as this code will only spawn platforms once, but i want to keep spawning platforms, plus my blockCount variable actually counting that how many platforms i've spawned as if i keep spawning them then the end user's phone will freeze after some time ... yes you are right as nameInt was useless but it was not always one as in actual code it is changing it's value to make spawned platform's name different from last spawned platform ... i agree to your advice of using member variables ... if you wanna know wat i m working upon then wait for sometime and i will upload it here ... https://play.google.com/store/apps/developer?id=$$anonymous$$emoth+Games

avatar image
0

Answer by centaurianmudpig · Dec 02, 2015 at 04:35 PM

You set the worldPosVec in case 1 and case 2, you don't set the worldPosVec in case 0. So it will use the value as defined on line 23, which is exactly the same as on line 54 and 55 of case 2.

You need to take more care when writing your code. Following the program flow and checking the state of values is an important aspect of programming. Use compiler debugging and Debug.Log() to help in your efforts.

Comment
Add comment · Show 4 · 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
avatar image aditya · Dec 03, 2015 at 06:29 AM 0
Share

i didn't set the worldVec in case 0 coz i wanna use the values i used to initialize this vector, and this is working all fine at runtime ... actually it is case 1 and case 2 which is experiencing some problem, these two cases instantiating the platforms in center of the screen, and when i tried to print the values of spawnPos from case 1 and case 2, i've got the correct values which i need to instantiate my platforms on my desired positions ... this means that worldVec giving me correct values but my platforms are not instantiating on correct positions

avatar image Bonfire-Boy aditya · Dec 03, 2015 at 10:43 AM 0
Share

So what do you want case 0 to do? It's using spawnPos for the position, but cases 1 and 2 set spawnPos to something else, so as soon as you've hit one of those cases, you've lost that initial value. Seems all wrong to me, I can't see any reason to make case 0 work differently to the others.

avatar image aditya Bonfire-Boy · Dec 04, 2015 at 06:42 AM 0
Share

actually this program is looking so stupid because i tried everything i could with to make this program work but with no success, so at last i decided to spawn first three platforms with some predefined values and then after that i only increasing or decreasing the Y values keeping X & Z same, so in case 0 platform is using the initialized value which is at Top Left of the screen, case1 is using $$anonymous$$iddle Bottom, case 2 Top Right, and then after that it is just increasing or decreasing the Y values

avatar image aditya · Dec 03, 2015 at 06:38 AM 0
Share

one more thing i wanna clarify here is that the values of worldVec on line 23 and on lines 54 and 55 are not same as on line 23 worldVec is 10% of screen width and 90% of height while on lines 54 & 55 they are different

avatar image
0

Answer by meat5000 · Dec 03, 2015 at 02:14 PM

 lastObjects[i] = (GameObject)Instantiate(platforms[j], spawnPos, Quaternion.identity) as GameObject;
 lastObjects[i].transform.position = //etc

As a last resort/backup simply reposition the objects after Instantiation.

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
avatar image
0

Answer by aditya · Dec 04, 2015 at 06:37 AM

thanks @centaurianmudpig @Bonfireboy @wibble88 and @meat5000 for your quick replies, after the answer of @centaurianmudpig i rewrite the whole program again and i don't know how (magically) the program working all fine, but only on PC and i m facing the same problem on my android phone (ASUS zenfone 5) for which i asked this question, so now i m going with @wibble88 suggestion, as it might be the problem with platforms coz i was trying to make this game for TABs too and for that i used high resolution sprites (of about 0.7 mb for one sprite) and my phone might not getting enough time to calculate and spawn, plus the game freezes and lagging on phones ... plus i m going to use the idea of @meat5000 too as i will change the positions of platforms after spawning them ...

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

41 People are following this question.

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

Related Questions

How can I Instantiate two new GameObjects at the same time? (Attempting Asteroids style game) 2 Answers

Instantiation and Deletion very slow... HELP.. 3 Answers

Canvas Element - Scales with screen size, but not clickable (2D) 2 Answers

[Shooting shots Scripting] How to make the compiler know that I mean the empty quad by the Public Transform? 0 Answers

You should NOT release this unfinished software... 0 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