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