• 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 aldridgedsm · May 15, 2012 at 07:00 PM · prefabscounterswitching

Randomly switching between prefabs

hi guys,

I'm a total noob at unity so I hope this question isn't too dumb,

I have made 3 prefabs each with different scripts attached (c#) and I need them to switch randomly between one another. For example, I have a platform block (with certain properties in the script)and I need it to possibly "become" another type of block with a different script attached or even stay the same.

I there any way to do this? I would also be helpful if this were attached to a counter so that it would change say, every 5 seconds.

I would be very grateful for your help but like I say I am new so you may have to spell it out LOL.

Thanks

(I'm coding in c#)

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

3 Replies

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

Answer by bompi88 · May 15, 2012 at 08:11 PM

You can for example make an empty GameObject, and make each block child of that empty. Then you can activate random blocks from a script attached to the empty. I have created an example script you can attach your empty GameObject. If the blocks have to repositioning or something like that each time before the block is activated, you can create a StartOver function in the scripts attached to the blocks. Then just call that function from the script attached to the empty. Maybe not the best way to do it, but I think it should work. I assumed the mesh and/or material in each prefab were different from the other prefabs' mesh, and a property script is attached in each prefab.

 using UnityEngine;
 using System.Collections;
 
 public class BlockSwitcher : MonoBehaviour {
     public float secondsToNextBlock = 5.0f;
     private Transform[] blocks;
     private bool timeToChange = false;
     private int currentBlock = 1;
     
     void Awake () {
         blocks = gameObject.GetComponentsInChildren<Transform>();
 
     }
     
     void Start () {
         foreach (Transform t in blocks) {
             if (t.gameObject!=gameObject)
                 t.gameObject.active = false;
         }
         timeToChange = true;
     }
     
     void Update () {
         if (timeToChange) {
             timeToChange = false;
             StartCoroutine("ChangeBlock");
         }
     }
     
     IEnumerator ChangeBlock () {
         blocks[currentBlock].gameObject.active = false;
         currentBlock = Random.Range(1,blocks.Length);
         blocks[currentBlock].gameObject.active = true;
         
         yield return new WaitForSeconds(secondsToNextBlock);
         timeToChange = true;
     }
     
 }
Comment
Add comment · Show 1 · 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 aldridgedsm · May 17, 2012 at 09:48 AM 0
Share

thanks man

avatar image
0

Answer by Starwalker · May 15, 2012 at 08:05 PM

As far as I understand from your question, your trying to randomly change a "Script" attached to a prefab depending on some condition or randomly.

I don't know if it is possible to remove a script which is already applied to a prefab but as a solution I could suggest you make a "switch case" combining the 3 or 4 scripts your trying to jump between in a single file.

The randomness of the number can be taken from here. (you would need to typecast or round off the randomness to an int which the switch case would use)

Hope it helps, I have not tried this myself though.

Comment
Add comment · Show 2 · 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 asafsitner · May 15, 2012 at 08:30 PM 0
Share

Actually Random.Range has an overload that takes and returns integer types so there's no need for rounding.

avatar image aldridgedsm · May 15, 2012 at 08:52 PM 0
Share

to clarify both the script and game object contained in the prefab have to change

sorry for the confusion

avatar image
0

Answer by asafsitner · May 15, 2012 at 08:29 PM

To make a counter - or make something happen every X seconds - there are a few approaches. You can use a decremented float with Time.deltaTime, have an infinite loop with a yield instruction or just use InvokeRepeating etc.

Some approaches are demonstrated in this script here:

 using UnityEngine;
 System.Collections;
     
 class TimerExamples: MonoBehaviour
 { 
 
     //array of supplied prefabs to choose from
     public GameObject[] PrefabPool;
 
     //arbitrary value to demonstrate the difference between first invoke and future invokes
     public float TimeToFirstInvoke = 2;
     
     //the time to wait between future invokes beyond the first
     public float FutureInvokeInterval = 5;
 
     //the actual timer
     public float RunningTimer;
     
     // Use this for initialization
     IEnumerator Start()
     {
         //resetting the timer to the initial value
         RunningTimer = FutureInvokeInterval;
            
         //this will invoke the black magic method after the TimeToFirstInvoke, and then every FutureInvokeInterval seconds
         InvokeRepeating("BlackMagicMethod", TimeToFirstInvoke, FutureInvokeInterval);
     
         //wait for the first invoke
         yield return new WaitForSeconds(TimeToFirstInvoke);
 
         BlackMagicMethod();
            
         //this loop will run forever, calling the black magic method every FutureInvokeInterval seconds
         while (true)
         {
             BlackMagicMethod();
   
             //wait for the interval between future invokes
             yield return new WaitForSeconds(FutureInvokeInterval);
         }
     }
     
     // Update is called once per frame
     void Update()
     {
         if (RunningTimer > 0)
         {
             //this will decrement the timer gradually over time
             RunningTimer -= Time.deltaTime;
         }
         else
         {
             //this resets the timer 
             RunningTimer = FutureInvokeInterval;
     
             BlackMagicMethod();
         }
     }
 
     /// <summary>
     /// this method switches the current prefab with a random one from the supplies array
     /// by instantiating the substitute and then killing the current prefab
     /// </summary>
     void BlackMagicMethod()
     {
         //first instantiate the substitute, choosing a random prefab from the array
         Instantiate(PrefabPool[Random.Range(0, PrefabPool.Length)], transform.position, transform.rotation);
 
         //we destroy the gameObject and not the transform or 'this' because 
         //those would only destroy the component and we want to get rid of everything
         Destroy(gameObject);
     }
 }

The BlackMagicMethod first creates a substitute for the existing prefab by choosing a random prefab from the supplied array and then kills the current object this script is attached to to create the illusion of a 'switch' between prefabs.

It's not the perfect approach, and obviously you should never actually attach this script to anything (unless you want three separate calls to the BlackMagicMethod), it's here to demonstrate a point. Or three. :)

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

7 People are following this question.

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

Related Questions

Switching between prefabs 0 Answers

Prefabs Empty After Crash 2 Answers

Help with ITween multiple objects on path with slightly random path points 0 Answers

Cannot remove a prefab using OnCollisionEnter function. 1 Answer

Changes to variables in script not being modified on objects attached to 1 Answer


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