Error cs0117 random does not contain a definition for range

Нужно, чтобы переменной присваивалось случайное значение, в заданных мною пределах.

Правильное использование Random’a

Нужно, чтобы переменной присваивалось случайное значение, в заданных мною пределах.

Я делал вот так:

Ошибка: Assets/Random.cs(15,28): error CS0117: `Random’ does not contain a definition for `Range’

Что я делаю не так? И как вообще осуществить, то что я написал? Заранее спасибо.

Error
UNIт
 
Сообщения: 66
Зарегистрирован: 25 авг 2015, 10:39

Re: Правильное использование Random’a

Сообщение beatlecore 13 мар 2016, 11:07

x = Random.Range(0.0f, 10.0f);

Аватара пользователя
beatlecore
Старожил
 
Сообщения: 964
Зарегистрирован: 05 фев 2013, 21:26
Откуда: Sun Crimea
Skype: beatlecore

Re: Правильное использование Random’a

Сообщение Error 13 мар 2016, 18:49

Assets/Random.cs(15,28): error CS0117: `Random’ does not contain a definition for `Range’
Та же ошибка…

Error
UNIт
 
Сообщения: 66
Зарегистрирован: 25 авг 2015, 10:39

Re: Правильное использование Random’a

Сообщение waruiyume 13 мар 2016, 19:02

Либо так: x = UnityEngine.Random.Range(10.0f);
либо, using Random = UnityEngine.Random

Аватара пользователя
waruiyume
Адепт
 
Сообщения: 6059
Зарегистрирован: 30 окт 2010, 05:03
Откуда: Ростов на Дону

Re: Правильное использование Random’a

Сообщение Error 13 мар 2016, 19:15

в первом случае ошибка: Assets/Random.cs(15,40): error CS1501: No overload for method `Range’ takes `1′ arguments

второй не совсем понял как использовать, какой переменной там вообще будет присваиваться значение и где указать предел значений.

Error
UNIт
 
Сообщения: 66
Зарегистрирован: 25 авг 2015, 10:39

Re: Правильное использование Random’a

Сообщение Error 13 мар 2016, 19:17

Всё вроде получилось я во 2 просто аргумент ещё указал: (10.0f, 20.0f). Спасибо большое!

Error
UNIт
 
Сообщения: 66
Зарегистрирован: 25 авг 2015, 10:39


Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: Google [Bot] и гости: 6



По туториалу собираю Tower Defence на Unity для себя и на моменте создания скрипта для башен получаю ошибки CS0117 и CS0122.
Туториал супер наглядный, там просто пишется код и дополнительно объясняется что к чему.
По итогу его написания у человека все работает, у меня ошибки.
Дословно выглядят они так:

1) AssetsScriptsTower.cs(26,41): error CS0117: ‘Enemies’ does not contain a definition for ‘enemies’

2) AssetsScriptsTower.cs(51,21): error CS0122: ‘Enemy.takeDamage(float)’ is inaccessible due to its protection level

Сам Код:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tower : MonoBehaviour
{
   [SerializeField] private float range;
   [SerializeField] private float damage;
   [SerializeField] private float timeBetweenShots; // Time in seconds between shots

    private float nextTimeToShoot;

    private GameObject currentTarget;

    private void Start()
    {
        nextTimeToShoot = Time.time;
    }

    private void updateNearestEnemy()
    {
    GameObject currentNearestEnemy = null;

    float distance = Mathf.Infinity;

    foreach(GameObject enemy in Enemies.enemies)
        {
            float _distance = (transform.position - enemy.transform.position).magnitude;

            if (_distance < distance)
            {
                distance = _distance;
                currentNearestEnemy = enemy;
            }
        }

    if (distance <= range)
        {
            currentTarget = currentNearestEnemy;
        }
    else
        {
            currentTarget = null;
        }
    }

    private void shoot()
    {
        Enemy enemyScript = currentTarget.GetComponent<Enemy>();

        enemyScript.takeDamage(damage);
    }

    private void Update()
    {
        updateNearestEnemy();

        if (Time.time >= nextTimeToShoot)
        {
            if (currentTarget != null)
            {
                shoot();
                nextTimeToShoot = Time.time + timeBetweenShots;
            }
        }
    }
}

C# Compiler Error

CS0117 – ‘type’ does not contain a definition for ‘identifier’

Reason for the Error

This error can be seen when you are trying to reference an identifier that does not exist for that type. An example of this when you are trying to access a member using base. where the identifier doesnot exist in the base class.

For example, the below C# code snippet results with the CS0117 error because the the identifier Field1 is accesses using base.Field1 but it doesnot exist in the base class “Class1”.

namespace DeveloperPublishNamespace
{
    public class Class1
    {

    }
    public class Class2 : Class1
    {
        public Class2()
        {
            base.Field1 = 1;
        }
    }
    public class DeveloperPublish
    {
        public static void Main()
        {
            
        }
    }
}

Error CS0117 ‘Class1’ does not contain a definition for ‘Field1’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 11 Active

C# Error CS0117 – 'type' does not contain a definition for 'identifier'

Solution

To fix the error code CS0117, remove the references that you are trying to make which is not defined in the base class.

Содержание

  1. Как исправить ошибки CS0117 и CS0122?
  2. Ошибка CS0117 в Unity.
  3. Ошибка CS0117 в Unity.

Как исправить ошибки CS0117 и CS0122?

По туториалу собираю Tower Defence на Unity для себя и на моменте создания скрипта для башен получаю ошибки CS0117 и CS0122.
Туториал супер наглядный, там просто пишется код и дополнительно объясняется что к чему.
По итогу его написания у человека все работает, у меня ошибки.
Дословно выглядят они так:

1) AssetsScriptsTower.cs(26,41): error CS0117: ‘Enemies’ does not contain a definition for ‘enemies’

2) AssetsScriptsTower.cs(51,21): error CS0122: ‘Enemy.takeDamage(float)’ is inaccessible due to its protection level

  • Вопрос задан 13 мая 2022
  • 166 просмотров

Простой 1 комментарий

1 — у тебя в классе Enemies нет члена enemies. Возможно его нет совсем, а возможно у тебя опечатка.
2 — у тебя в классе Enemy есть метод takeDamage, но он не публичный

PS: На будущее:
— отмечай комментарием, на какой именно строке сработала ошибка
— не забывай заворачивать код в тег — это сильно упростит чтение для тех, кто попробует решить твой вопрос
— перед тем как задавать вопрос — попробуй загуглить в чём суть ошибки, и попробуй сам решить (CS0117, CS0122)
— перед тем как начинать писать на юнити, лучше всё-таки хоть самые основы C# изучить. Тут как в математике — без понимания простых вещей, ты гарантированно не сможешь понять сложные вещи.

Источник

Ошибка CS0117 в Unity.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class движение : MonoBehaviour
<
public float speed;
public float jumpForce;
public float moveInput;

public Joystick joystick;

private Rigidbody2D rb;

private bool facingRight = true;

private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;

private void Start()
<
rb = GetComponent ();
>

private void FixedUpdate()
<
moveInput = joystick.Horizontal;
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if(facingRight == false && moveInput > 0)
<
Flip();
>
else if(facingRight == true && moveInput = .5f)
<
rb.velocity = Vector2.up * jumpForce;
>
>

void OnCollisionEnter2D(Collision2D shit)
<
if (shit.gameObject.tag == «враг»)
<
ReloadFuckingLevel ();
>
>

void ReloadFuckingLevel()
<
Application.LoadLevel (Application.loadLevel); //здесь ошибка
>

void Flip()
<
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
>
>

cs(63,44): error CS0117: ‘Application’ does not contain a definition for ‘loadLevel’ это целиком ошибка. Помогите пожалуйста.

Источник

Ошибка CS0117 в Unity.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class движение : MonoBehaviour
<
public float speed;
public float jumpForce;
public float moveInput;

public Joystick joystick;

private Rigidbody2D rb;

private bool facingRight = true;

private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;

private void Start()
<
rb = GetComponent ();
>

private void FixedUpdate()
<
moveInput = joystick.Horizontal;
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if(facingRight == false && moveInput > 0)
<
Flip();
>
else if(facingRight == true && moveInput = .5f)
<
rb.velocity = Vector2.up * jumpForce;
>
>

void OnCollisionEnter2D(Collision2D shit)
<
if (shit.gameObject.tag == «враг»)
<
ReloadFuckingLevel ();
>
>

void ReloadFuckingLevel()
<
Application.LoadLevel (Application.loadLevel); //здесь ошибка
>

void Flip()
<
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
>
>

cs(63,44): error CS0117: ‘Application’ does not contain a definition for ‘loadLevel’ это целиком ошибка. Помогите пожалуйста.

Источник

Topic: Random errors  (Read 2274 times)

Hi there,
Imported a new package and started getting these errors:

Assets/NGUI/Scripts/Interaction/UIButtonPlayAnimation.cs(39,52): error CS0117: `Direction’ does not contain a definition for `Forward’
Assets/NGUI/Scripts/Interaction/UIButtonTween.cs(38,52): error CS0117: `Direction’ does not contain a definition for `Forward’
Assets/NGUI/Scripts/Internal/ActiveAnimation.cs(39,46): error CS0117: `Direction’ does not contain a definition for `Toggle’
Assets/NGUI/Scripts/Internal/ActiveAnimation.cs(40,49): error CS0117: `Direction’ does not contain a definition for `Toggle’

I’ve tried to re-import NGUI by completely deleting the folder and all of it’s components, but no luck.

Any help would be appreciated.

Thanks!


Logged


kevork

Quick guess, the new package you imported has a type named Direction.

You can either change the name of that type (or put it in a different namespace) or change Direction to AnimationOrTween.Direction on the NGUI lines where you have an error.


Logged


I was considering this, but didn’t want to blow it all up haha. Will give it a go.

Thanks


Logged


After giving it a try, I’m having a little trouble. I now get this error:
Assets/NGUI/Scripts/Interaction/UIButtonPlayAnimation.cs(39,16): error CS0246: The type or namespace name `Direction1′ could not be found. Are you missing a using directive or an assembly reference?

Which, of course is expected but I can’t find where Direction is originally declared :(


Logged


You renamed the wrong class.

Delete NGUI.

Find the «Direction» class.

Rename it to something else using refactoring (not just renaming the file!)

Re-import NGUI.


Logged


Понравилась статья? Поделить с друзьями:
  • Error cs0117 debug does not contain a definition for log
  • Error cs0117 console не содержит определение для readline
  • Error cs0117 console does not contain a definition for writeline
  • Error cs0117 camera does not contain a definition for main
  • Error cs0116 как исправить