Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 sup4scripter · Jul 17, 2012 at 03:53 PM · guiarrayrandomstring

how to randomly pick a string from an array

I am really new to scripting and I want to create a list of names and then when I start the game the program picks a random name and shows it to me. I prefer in a GUI Label. this is the code I tried:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class random : MonoBehaviour {
  
 string[] names = new List { "player1", "player2", "player3", "player4", "player5" };
 
 int index = random.Next(strings.Count);
 var name = names[index];
 void OnGUI ()
  {
  GUILayout.Label (name);
  }
  
 
 
 }`

but it gave me this error:

The contextual keyword `var' may only appear within a local variable declaration

Please help me

Comment
Add comment · Show 3
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 UTeam · Apr 14, 2014 at 01:03 PM 0
Share

Hi

I am currently have the same issue.

I have used the code from above, but are getting this error: A field initializer cannot reference the non-stratic field, method, or property texts

The code:

 string[] texts = new string[] { "player1", "player2", "player3", "player4", "player5" };
     
 string name = texts[Random.Range(0, names.Length - 1)];
avatar image BrinkHouseGames UTeam · Jul 24, 2014 at 06:32 AM 0
Share

For those people who may see this and wonder the answer.

The error is thrown because 'name' is referencing a property that hasn't been created yet. Properties initializers (texts) run after field initializers (name). In a nutshell, you can't initialise a variable with any other class level value, unless it's static.

Assign in a constructor, ins$$anonymous$$d:

 string[] texts = new string[] { "player1", "player2", "player3", "player4", "player5" };
  
 string name = null;
 
 public $$anonymous$$yClass()
 {
     name = texts[Random.Range(0, names.Length - 1)];
 }
 
 
avatar image king_ UTeam · Jul 24, 2014 at 02:35 PM 0
Share

if you need everything in the array use

 array.Lenght;

if you dont need the last object in the array

 array.Lenght - 1;



3 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by captaincrunch80 · Jul 17, 2012 at 05:01 PM

Your class random has no such function. It has only the variables and methods inherited from MonoBehaviour.

You should not use var in C#. Use the type string in this case.

What you want is the class method Range of Class Random.

  string name = names[Random.Range(0, names.length -1)];


Here are the docs for Random.Range http://docs.unity3d.com/Documentation/ScriptReference/Random.Range.html

Comment
Add comment · Show 3 · 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 captaincrunch80 · Jul 17, 2012 at 06:16 PM 0
Share

Also you should not call your class random.

Name it after what it is in a higher abstraction and have a capital letter at the beginning to stick to name conventions.

It picks a player by random. So the highest abstraction of that would be something like class RandomPlayerSelection.

But I believe it is just a test class, so its purpose will change later, or it is throw away code. Nevertheless, random is not a good class name for this and there already exits a class called Random. So coding errors are guaranteed.

avatar image Burak13 · Aug 25, 2020 at 03:12 PM 0
Share

It should be names.Length with capital "L". If anyone have trouble with this.

avatar image farmerdwight · Sep 11, 2020 at 07:10 AM 0
Share

You should not subtract 1 from the length. The Range function operates with the $$anonymous$$ inclusive and the max exclusive.

avatar image
0

Answer by Graham-Dunnett · Jul 17, 2012 at 04:01 PM

var is a keyword that Javascript uses to introduce a new variable declaration. C# does not use this keyword. Instead do something like:

 string name = names[index];

Note that you have some code outside of any function. That's bad. Instead, put that code inside the Start() function. Unity will call Start() when your game object that has this script attached is created. The name variable is needed by your OnGUI() so declare it outside of Start and OnGUI.

Comment
Add comment · Show 5 · 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 Graham-Dunnett ♦♦ · Jul 17, 2012 at 04:02 PM 2
Share

Well, c# does have a var keyword. Don't use it until you know what it's for. It's better to provide the type for your variables.

avatar image Meltdown · Jul 17, 2012 at 04:03 PM 0
Share

Incorrect.. C# type inference has been around C# 3.0. And you can use the var keyword safely in C# in Unity. With certain rules of course.. http://stackoverflow.com/questions/479883/how-good-is-the-c-sharp-type-inference

avatar image Graham-Dunnett ♦♦ · Jul 17, 2012 at 04:07 PM 0
Share

(I was trying to keep it simple.)

avatar image Meltdown · Jul 17, 2012 at 04:10 PM 0
Share

oh lol, what have I done :(

avatar image sup4scripter · Jul 17, 2012 at 04:46 PM 0
Share

I got more errors now 1 red error:`random' does not contain a definition for `Next' and two yellow which are also about random.name

avatar image
0

Answer by Meltdown · Jul 17, 2012 at 06:05 PM

You have lots of errors in your script. I'd suggest doing a C# beginners tutorial to understand what is going on, we can't really help you with such basics all the time. I'd suggest getting a 1 month subscription to lynda.com and doing the C# essentials training video course.

Basically you need to change these lines..

 int index = random.Next(strings.Count);
 var name = names[index];

to

 int index = Random.Range(0, names.Length - 1);
 string name = names[index];


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 sup4scripter · Jul 17, 2012 at 08:00 PM 0
Share

You are right about beginners tutorials still thx for help

avatar image sup4scripter · Jul 17, 2012 at 08:02 PM 0
Share

still needed to change something but got it working now thx again

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.

Follow this Question

Answers Answers and Comments

10 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

Related Questions

How to create a random array avoiding repeat same value 1 Answer

Unity Shutdown 1 Answer

Assigning array element to variable 1 Answer

How to output a file to a single string? 1 Answer

Setting variable to random string from an array? 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