Error cs0723 cannot declare a variable of static type random

This repository contains .NET Documentation. Contribute to dotnet/docs development by creating an account on GitHub.

Permalink

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

docs/docs/csharp/misc/cs0723.md

Go to file

  • Go to file

  • Copy path


  • Copy permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0723

Compiler Error CS0723

07/20/2015

CS0723

CS0723

b9f6aebc-e959-407d-8d5c-6a6dcabcfe0f

Compiler Error CS0723

Cannot declare variable of static type ‘type’

Instances of static types cannot be created.

The following sample generates CS0723:

// CS0723.cs  
public static class SC  
{  
}  
  
public class CMain  
{  
   public static void Main()  
   {  
      SC sc = null;  // CS0723  
   }  
}  

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

1

Как воспроизводить случайную музыку?

11.09.2021, 12:39. Показов 4070. Ответов 33


Добрый день!!! Я хочу сделать кнопку UI, при нажатии которой будет проигроваться рандомная музыка(те музыкальные клипы которые я укажу), помогите пж в написании скрипта.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

11.09.2021, 13:10

2

массив аудио клипов и воспроизводишь с помощью AudioSourse клип из массива.рандом между нулевым элементом и массив.length(длина массива)



0



DeadRider

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

11.09.2021, 13:48

 [ТС]

3

можно пожалуйста поточнее, вот скрипт но я думаю что это вообще не правильно

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Collections;
 
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class audioo : MonoBehaviour
{
    public string Audio;
    public AudioSource Audio_;
 
    public void GenerateAudio()
    {
        Audio_.outputAudioMixerGroup = Audio[Random.Range(0, Audio.Length)];
    }
}



0



Gammister

216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

11.09.2021, 15:08

4

чуть не так , как я объяснял
думаю Audio должно быть типом AudioClip а не строкой.

C#
1
2
3
4
5
6
7
8
public AudioClip[] audioClips;
public AudioSource sourse;
 
Update()
{
// если например нажата клавиша
sourse.Play( 0, audioClips.Length));
}

Добавлено через 34 секунды
или вот тема с данного форума:
Выбор рандомного звука

Добавлено через 17 секунд
в проекте не проверял, но примерно так

Добавлено через 9 минут
код не рабочий что я вставил. сори

Добавлено через 1 минуту
суть такова, что рандомно вытягиваешь элемент и воспроизводишь по рандому индекса.

Добавлено через 11 минут
так работает. проверил

C#
1
2
3
Random rnd = new Random();
 
        sourse.PlayOneShot(audioClips[rnd.Next(audioClips.Length)]);



0



DeadRider

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

11.09.2021, 18:54

 [ТС]

5

Сори, чето опять не догоняю. Только начал программировать, Помоги пж.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class audioo : MonoBehaviour
 
{
    public AudioClip[] audioClips;
    public AudioSource sourse;
    
 
 
    private void Update()
    {
        Random rnd = new Random();
 
    sourse.PlayOneShot(audioClips[rnd.Next(audioClips.Length)]);
    }
    
 
}



0



Gammister

216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

11.09.2021, 19:30

6

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class audioo : MonoBehaviour
{
public AudioClip[] audioClips;
public AudioSource sourse;
 
private void Update()
{
if (Input.GetKeyUp(KeyCode.Space) & isGround){// помещаем это в условие отпускания клавиши Space
                                                          // у тебя может быть любое событие
     Random rnd = new Random();
 
     sourse.Play(audioClips[rnd.Next(audioClips.Length)]);
}
}
 
 
}

вешаешь скрипт на пустышку или любой нужный тебе объект и в поле с массивом клипов затаскиваешь нужные аудио файлы.
только компонент AudioSource тоже должен быть на объекте. он и воспроизводит звуки с массива audioClips. его тоже
перетащишь в поле sourse.
все ))

Добавлено через 17 минут

Цитата
Сообщение от Gammister
Посмотреть сообщение

& isGround

это нужно убрать из условия. работать не будет. это из другого кода



0



DeadRider

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

12.09.2021, 09:38

 [ТС]

7

Привет!!! Выдает ошибку

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Random rnd = new Random();  
sourse.Play(audioClips[rnd.Next(audioClips.Length)]);
        
 
public class audioo : MonoBehaviour
{
    public AudioClip[] audioClips;
    public AudioSource sourse;
 
    private void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space))
            
    }
 
}

Severity Code Description Project File Line Suppression State
Error CS1023 Embedded statement cannot be a declaration or labeled statement Assembly-CSharp C:UsersИльяOneDriveРабочий столUnity2DGameAssetsaudioo.cs 14 Active
Error CS0723 Cannot declare a variable of static type ‘Random’ Assembly-CSharp C:UsersИльяOneDriveРабочий столUnity2DGameAssetsaudioo.cs 14 Active
Error CS0712 Cannot create an instance of the static class ‘Random’ Assembly-CSharp C:UsersИльяOneDriveРабочий столUnity2DGameAssetsaudioo.cs 14 Active
Error CS0103 The name ‘rnd’ does not exist in the current context Assembly-CSharp C:UsersИльяOneDriveРабочий столUnity2DGameAssetsaudioo.cs 15 Active



0



Gammister

216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

12.09.2021, 11:22

8

первые две строчки верни обратно

Добавлено через 4 минуты

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        
public class audioo : MonoBehaviour
{
    public AudioClip[] audioClips;
    public AudioSource sourse;
 
    private void Update()
    {
       if (Input.GetKeyUp(KeyCode.Space))
       {
            Random rnd = new Random();  
            sourse.Play(audioClips[rnd.Next(audioClips.Length)]);
       }           
    }
}

и со скобками намутил



0



DeadRider

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

12.09.2021, 11:49

 [ТС]

9

все так и сделал, опять ошибку выдает(, сори что покоя не даю

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class audioo : MonoBehaviour;
{
    public AudioClip[] audioClips;
    public AudioSource sourse;
 
    private void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space))
        {
            Random rnd = new Random();
            sourse.Play(audioClips[rnd.Next(audioClips.Length)]);
        }
    }
}



0



Gammister

216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

12.09.2021, 12:01

10

какую ? переводи ошибки. и номер строки где ошибка тоже дается.

Добавлено через 4 минуты
попробуй вместо

C#
1
sourse.Play(audioClips[rnd.Next(audioClips.Length)]);

прописать рандом обычным Unity рандомом

C#
1
sourse.Play(audioClips[Random.Range(0, audioClips.Length)]);

Добавлено через 1 минуту
ругался на способ применения рандома

Добавлено через 2 минуты
но у меня так работало



0



DeadRider

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

12.09.2021, 12:08

 [ТС]

11

ошибка
Error CS1503 Argument 1: cannot convert from ‘UnityEngine.AudioClip’ to ‘ulong’

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class audioo : MonoBehaviour
{
    public AudioClip[] audioClips;
    public AudioSource sourse;
 
    private void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space))
        {
            
            sourse.Play(audioClips[Random.Range(0, audioClips.Length)]);
 
        }
    }
}



0



Gammister

216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

12.09.2021, 12:09

12

и надеюсь у тебя в самом верху есть библиотеки…

C#
1
2
3
using System.Collections;
using System.Collections.Generic;
using UnityEngine;



0



DeadRider

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

12.09.2021, 12:25

 [ТС]

13

Естественно есть…

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
 
 
 
public class audioo : MonoBehaviour
{
    public AudioClip[] audioClips;
    public AudioSource sourse;
 
    private void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space))
        {
            
            sourse.Play(audioClips[Random.Range(0, audioClips.Length)]);
 
        }
    }
}



0



Gammister

216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

12.09.2021, 12:53

14

добавь еще эту библу

C#
1
using Random = System.Random;

Добавлено через 1 минуту
вариант с

C#
1
2
    
sourse.Play(audioClips[rnd.Next(audioClips.Length)]);

должен заработать. забыл ))



0



DeadRider

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

12.09.2021, 18:54

 [ТС]

15

ошибки Severity Code Description
The name ‘rnd’ does not exist in the current context

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
using Random = System.Random;
 
 
 
public class audioo : MonoBehaviour
{
    public AudioClip[] audioClips;
    public AudioSource sourse;
 
    private void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space))
        {
 
            sourse.Play(audioClips[rnd.Next(audioClips.Length)]);
 
 
        }
    }
}



0



529 / 341 / 196

Регистрация: 18.10.2019

Сообщений: 1,152

12.09.2021, 19:43

16

DeadRider, поменяй rnd на Random



0



216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

13.09.2021, 00:06

17

Цитата
Сообщение от BattleCrow
Посмотреть сообщение

поменяй rnd на Random

советовал. у него так не работает.



0



DeadRider

1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

13.09.2021, 12:09

 [ТС]

18

И что делать тогда?

Добавлено через 34 секунды
И что делать тогда???

Добавлено через 1 час 15 минут
ошибка: An object reference is required for the non-static field, method, or property ‘Random.Next(int)’

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
using Random = System.Random;
 
 
 
public class audioo : MonoBehaviour
{
    public AudioClip[] audioClips;
    public AudioSource sourse;
 
    private void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space))
        {
 
            sourse.Play(audioClips[Random.Next(audioClips.Length)]);
 
 
        }
    }
}



0



216 / 173 / 56

Регистрация: 07.05.2017

Сообщений: 1,341

13.09.2021, 12:21

19

покажи скрины проекта. как там у тебя устроено. или создай новый скрипт пустой и скопируй в него всю эту логику.
только создавай обычным способом, через создать / C# скрипт. заметил такую фишку что создавая скрипты через добавить компонент работает не нормально. рандом как раз не работает. не знаю с чем это связано и когда пофиксят.
ты каким способом создаешь ?



0



1 / 1 / 0

Регистрация: 09.09.2021

Сообщений: 34

13.09.2021, 12:36

 [ТС]

20

вот скрины проекта, скрипт создал новый, как ты и сказал, но проблема не устранилась

Миниатюры

Как воспроизводить случайную музыку?
 

Как воспроизводить случайную музыку?
 



0



Questions : Cannot create an instance of the static class Random

2023-02-06T13:11:58+00:00 2023-02-06T13:11:58+00:00

729

Hi Ive switched from regular coding to using solved uvdos c# Unity and Im getting errors for seemingly solved uvdos c# simple stuff. Here it is and Thanks in solved uvdos c# advance.

Error: Assets/Starting Biome.cs(8,18): error solved uvdos c# CS0712: Cannot create an instance of the solved uvdos c# static class ‘Random’

Error: Assets/Starting Biome.cs(8,7): error solved uvdos c# CS0723: Cannot declare a variable of static solved uvdos c# type ‘Random’

Error: Assets/Starting Biome.cs(9,23): error solved uvdos c# CS1061: ‘Random’ does not contain a solved uvdos c# definition for ‘Next’ and no accessible solved uvdos c# extension method ‘Next’ accepting a first solved uvdos c# argument of type ‘Random’ could be found solved uvdos c# (are you missing a using directive or an solved uvdos c# assembly reference?)

Here’s my Code:

    using UnityEngine;
    using System.Runtime;

    public class StartingBiome : MonoBehaviour{
    // Start is called before the first frame update
    static void StrBiome(){
      var RndB = new Random();
      int StrB = RndB.Next();
    }
    void Start()
    {

    }
    // Update is called once per frame
    void Update()
    {

    }
    }

Total Answers 3

29

Answers 1 : of Cannot create an instance of the static class Random

There is the static class quotes uvdos c# UnityEngine.Random and there is quotes uvdos c# System.Random.

Since you have the

using UnityEngine;

in your script but not

using System;

for the compiler it is clear that you quotes uvdos c# are referring to UnityEngine.Random.


Now you can either use explicitly

var RndB = new System.Random();
var StrB = RndB.Next();

Or add a

using Random = System.Random;

at the top of your script and then use quotes uvdos c# what you have.

var RndB = new Random();
var StrB = RndB.Next();

The UnityEngine.Random is specifically quotes uvdos c# made for float (Random.value). For int quotes uvdos c# values you have to go via quotes uvdos c# UnityEngine.Random.Range and to get the quotes uvdos c# same behavior as the System.Random.Next quotes uvdos c# (which only returns positive values) you quotes uvdos c# would have to rather do

using UnityEngine;

...

var StrB = Random.Range(0, int.MaxValue);

Now which of these two you chose is a quotes uvdos c# question of preference.

With the System.Random you create an quotes uvdos c# instance, use it once and throw it away quotes uvdos c# .. but that shouldn’t really matter in quotes uvdos c# your case.

0

2023-02-06T13:11:58+00:00 2023-02-06T13:11:58+00:00Answer Link

mRahman

5

Answers 2 : of Cannot create an instance of the static class Random

When using Unity, you should use Unity’s quotes uvdos c# own random number generator.
You can use quotes uvdos c# it like this:

StartingBiome.cs

using UnityEngine;

public class StartingBiome : MonoBehaviour
{
    // Start is called before the first frame update
    private static void StrBiome()
    {
        var strB = Random.Range(0, int.MaxValue);
    }

    private void Start()
    {
    }

    // Update is called once per frame
    private void Update()
    {
    }
}

This is the equivalent for C#’s quotes uvdos c# «random.Next()».
It returns a random quotes uvdos c# number within the Int32 range that is quotes uvdos c# equal or greater than 0. If you want to quotes uvdos c# use a smaller range, replace «0» with quotes uvdos c# the start of the range and quotes uvdos c# «int.MaxValue» with the end of the range quotes uvdos c# (start is inclusive, end is quotes uvdos c# exclusive).
You can also use floats. In quotes uvdos c# that case, both the start and the end of quotes uvdos c# the range are inclusive.

Happy coding!

0

2023-02-06T13:11:58+00:00 2023-02-06T13:11:58+00:00Answer Link

rohim

1

Answers 3 : of Cannot create an instance of the static class Random

For future readers: Both System.Random quotes uvdos c# and UnityEngine.Random work, but If you quotes uvdos c# are using Unity I would suggest using quotes uvdos c# Unity’s Random as it would be more quotes uvdos c# efficient. Here it is: int StrB = quotes uvdos c# Random.Range(min, max);. Massive thanks quotes uvdos c# to all the commenters
for being so kind quotes uvdos c# and helpful.

0

2023-02-06T13:11:58+00:00 2023-02-06T13:11:58+00:00Answer Link

rohim

Top rated topics

No naming conflict from two functions in global namespace (C++)?

Which is better, to start from higher load and reduce , or to gradually increase the load during stress test

Python sort a 2d list without using lambda

I am getting null pointer exception in page object class why I am getting NPE

Get columns from two dimensional array in java

In Typescript, why is an Omit type not a Partial type?

Fail to make a shared pointer from a reference

C language convert integer values to 0x.. hex byte values and store into an nx2 array

How to access cookies correctly in express application

How to map a json object into another new object

Parse error: syntax error, unexpected end of file in laravel

TypeError: sort_values() got an unexpected keyword argument ‘by’

How to resolve the Java Memory Heap issue for for each block

How can I trim a string if input is Ramesh-123-india …my desire output should be only «india»»

Notion js SDK asks for title even after title is provided

How to make a welcome message in discord.py for all servers?

Stream outside of the tx2 device

Functionalities between calling rpc methods

Spatie/Laravel-Settings Package

How to identify first appearance of items in Pyspark

How to improve the performance of Mapbox in a flutter

Change cell type of excel cells using Apache Poi 5.1

Returning List of Object from Repository by avoiding creation of entity class

Prompted for ssh passphrase after ever push/pull

Why can’t implicitly convert to a std::variant with std::atomic_bool

Error while using python open cv libary and keyboard libary

Styling Microsoft Graph img inside of Shadow-Root(open)

Excel Formula — If any cells within a range contain specific value, then

Archive command failed with exit code 1

Building a monthly Snapshot VIEW from historical data

How do I run Node.js code in a WordPress plugin?

Plot bar graph from colSums in R

Refresh token validation in microservice architecture

WriteXml not saving a file

How to apply custom font-size based on tailwindcss

How to give a security group access to cloudwatch and s3?

Updating d3 chart with new data, the old data points not removed

When I’m visiting another page, The images, logos, and icons are not displayed. In this project, I’m using the pug template engine and express.js

Chrome Extension «Uncaught Type Error: Cannot read properties of undefined (reading ‘query’) error». query property there was a mistake

ForEach Loop in Swift for Buttons

How to get Readiness Probe’s result in code?

Pytorch class weights for multi class classification

Oracle DB Create Table as Copy Vs. Merging Data into Empty Table

Is there a way to lock a specific block of code in PHP? so that users can access it one at a time

Import from node_modules into Svelte

Unchecking remove splash screen causes an error

User generic function to determine the instance type in swift

How can I find the observations associated with rank j in this code?

Is there way to route to home from a separate app hosted in a sub directory?

How set airflow DAG Concept scheduling

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

User2142845853 posted

this is similar to a question asked, but is different, 

Goal is to upload and save pdf files in sql server, (or save other formats), defined the Model: 

  [Key]
        public int ID { get; set; }
        [Display(Name = "File Name")]
        public string FileName { get; set; }
        [Display(Name = "File  ")]


        public Byte[] aFile { get; set; }
        [Display(Name = "File Date")]
        public DateTime filedate { get; set; }

        [Display(Name = "File Info ")]
        public string fileINFO { get; set; }
        [Display(Name = "file Owner ")]
        public string fileOWNER { get; set; }

varbinary(MAX)  is the type in the SQL server for the Byte[ ]

It runs, it made its own local db instance, i can create a new record, textbox fields for the items, but for ‘aFile’ the create method generated a textbox instance, although it does not get displayed,

<div class="form-group">
            @Html.LabelFor(model => model.aFile, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.aFile, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.aFile, "", new { @class = "text-danger" })
            </div>
        </div>

But then launching the  open file dialog and @{ FileStream fs = }  part to convert into a byte array, is there a jquery or angular directive that does this from within the html side?

Понравилась статья? Поделить с друзьями:
  • Error cs0619 guitexture is obsolete guitexture has been removed use ui image instead
  • Error cs0619 guitext is obsolete guitext has been removed use ui text instead
  • Error cs0619 eventtype mousedown is obsolete use mousedown instead unityupgradable mousedown
  • Error cs0579 повторяющийся атрибут system reflection assemblyversionattribute
  • Error cs0579 повторяющийся атрибут system reflection assemblycompanyattribute