Use of basic unity random numbers

Source: Internet
Author: User

Script Language: C #

A common example is that when the game's main character encounters an NPC in a scenario, the NPC will respond randomly. For example, if there is a 50% probability of a friendly greeting, the 25% probability will go away, 20% chance of attack and % chance of gift.

Create an npctest script to simulate the NPC action:

Using unityengine; using system. collections; public class npctest: monobehaviour {// NPC action probability float [] probarray = {0.5f, 0.25f, 0.2f, 0.05f}; int probvalue; // NPC selection value // use this for initialization void start () {}// update is called once per frame void Update () {}// select a function, returns the value of int choose (float [] probe) {float Total = 0.0f; For (INT I = 0; I <probe. length; I ++) {total + = probe [I];} // R Andom. the value method returns a random number float randompoint = random. value * Total; For (INT I = 0; I <probe. length; I ++) {If (randompoint <probe [I]) return I; else randompoint-= probe [I];} return probe. length-1;} void ongui () {If (GUI. button (New rect (10, 70, 50, 30), "click") {probvalue = choose (probarray); Switch (probvalue) {Case 0: Debug. log ("NPC pays tribute to me! "); Break; Case 1: Debug. Log (" NPC has left! "); Break; Case 2: Debug. Log (" NPC attacked me! "); Break; Case 3: Debug. Log (" NPC gave me money! "); Break; default: Debug. Log (" I have not met NPC "); break ;}}}}

Click the click button in the game view to view the printed data:

 

Reference link:

More detailed introduction: http://blog.csdn.net/luyuncsd123/article/details/16919547

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.