Error cs0117 console не содержит определение для readline

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

Содержание

  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’ это целиком ошибка. Помогите пожалуйста.

Источник

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

«class Program
{
static void Main()
{
//prompt user for mins
System.Console.Write(«Enter how many minuted you exercised: «);

string entry = System.Console.Readline();

//Add mins to total
//Display total mins
//Repeat until user quits

}

ERROR:
treehouse:~/workspace$ mcs Program.cs
Program.cs(8,35): error CS0117: System.Console' does not contain a definition forReadline’
/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)
Compilation failed: 1 error(s), 0 warnings

2 Answers

Steven Parker

C# is case-sensitive, and you wrote «Readline» (lower case «l») instead of «ReadLine» (capital «L»).

kyegrundy August 29, 2017 5:51pm

kittycat_13

2 / 2 / 0

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

Сообщений: 101

1

22.03.2015, 14:16. Показов 13632. Ответов 4

Метки нет (Все метки)


Здравствуйте. Такая проблема. Написала код, но программа выдает «System.Console» не содержит определение для «Writeline» (CS0117). Помогите, пожалуйста, исправить.

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
26
27
28
29
30
31
32
33
34
35
/*
 * Created by SharpDevelop.
 * User: Home
 * Date: 22.03.2015
 * Time: 12:58
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
 
namespace капит
{
    class Invesment
    {
        public static void Main(){
            int i;
        decimal amount, rate, profit, profit_i, win;
        amount = 15000.0m;
        rate = 0.15m;
        profit_i = 0;
        profit = amount/24*rate;
        Console.Writeline("Прибыль за первый месяц:" + profit);
        for (i=0; i<24; i++)
        {profit_i = profit_i + amount/24 * rate;
             amount = amount + profit_i;
             Console.WriteLine("Месяц:"+ (i+1) + "Прибыль за i-й месяц:" + profit_i + "Общая сумма:" + amount);
                               if (i == 23)
                               { win = profit_i - profit;
                                Console.WriteLine("Выигрыш от капитализации:" + win);
                                }
        
                       }
                }
               }
               }

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



0



AvizerScript

Заблокирован

22.03.2015, 14:18

2

Console.WriteLine — L большая должна быть



0



2 / 2 / 0

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

Сообщений: 101

22.03.2015, 14:22

 [ТС]

3

Скажите, пожалуйста, а как сделать, чтобы окно консоли оставалось на экране, а то оно постоянно пропадает?



0



AvizerScript

Заблокирован

22.03.2015, 14:25

4

C#
1
Console.ReadKey();

Добавьте после

C#
1
Console.WriteLine("Выигрыш от капитализации:" + win);



0



Prizrak86

52 / 52 / 18

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

Сообщений: 278

22.03.2015, 14:27

5

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

Скажите, пожалуйста, а как сделать, чтобы окно консоли оставалось на экране, а то оно постоянно пропадает?

В конце программы напиши

C#
1
Console.ReadLine();

Программа будет ожидать нажатия клавиши «Enter», по нажатию которой программа закроется.

Если написать

C#
1
Console.ReadKey();

Программа будет ожидать нажатие любой клавиши, и закроется при нажатии на любую клавишу.



1



I followed this thread to install Mono on my Fedora box:

Install Mono on Centos 5.5 using YUM

However, when I try and compile my program using:

 gmcs foo.cs

I get:

  foo.cs(11,44): error CS0117: `System.IO.File' does not contain a definition for `ReadLines'
/opt/novell/mono/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)

Compilation failed: 1 error(s), 0 warnings

The line in question is:

 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;

 foreach(int currentMax in File.ReadLines(args[0]).Select(int.Parse)) 
 {
     ...
 }

Can anyone point me in the right direction?

Community's user avatar

asked Dec 4, 2011 at 1:14

Jim's user avatar

3

So it looks like the problem is that you are using the gmcs compiler, which is designed specifically for targeting the .Net 2.0 runtime. The list of C# compilers for mono is:

  • mcs — .Net 1.1 runtime (deprecated)
  • gmcs — .Net 2.0 runtime
  • smcs — .Net 2.1 runtime
  • dmcs — .Net 4.0 runtime

(see here for more details)

So the compiler you should be using for targeting .Net 4.0 is dmcs. Instead, if you actually intended to target .Net 2.0, then use the File.ReadAllLines method that @kil and @minitech talked about.

answered Dec 4, 2011 at 2:47

Ken Wayne VanderLinde's user avatar

1

I believe you want File.ReadAllLines.

answered Dec 4, 2011 at 1:17

Ry-'s user avatar

Ry-Ry-

215k54 gold badges455 silver badges466 bronze badges

2

Формулировка задачи:

Хочу чтобы консоль закрывалась при нажатии клавиши,но выбивает ошибку.Если прописую Console.Read();или Console.ReadLine();все нормально,но мне это не подходит вот код:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
 
namespace ConsoleApp3
{
    public class Program
    {
        public void Main(string[] args)
        {
            Console.WriteLine("Привет");
            Console.ReadKey();
        }
    }
}

И еще подскажите как сделать чтобы консоль закрывалась при нажатии какой-то, клавиши к примеру (F).
Или как сделать чтобы консоль выполняла одно действие и только при нажатии клавиши продолжала выполнять следующее.

ТЕКСТ ОШИБКИ ИЗ VS:
Ошибка CS0117 «Console» не содержит определение для «ReadKey». ConsoleApp3.DNX Core 5.0
Спасибо.

Код к задаче: «CS0117 «Console» не содержит определение для «ReadKey». ConsoleApp3.DNX Core 5.0»

textual

Console.WriteLine("Привет");
 
ConsoleKeyInfo keyInfo;
do keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.F);
            
Console.WriteLine(keyInfo.KeyChar);

Полезно ли:

14   голосов , оценка 4.429 из 5

I don’t know why I am getting this error. I am using Repl.it at school since we are using chromebooks, but I don’t think the C# would be different. I’m debugging some code just to see what it looks like in the console, but it just simply won’t work. I am just getting errors. I’m using System.Diagnostics, System.IO, and System.

I know C# pretty well, so I don’t think I’m missing anything. I believe it’s just simply a Repl.it issue.

Here is my C# code:

public char firstchar = 'a';
public char lasrchar = 'z';

public int passwordLength = 6;
public long tries = 0;

public bool done = false;

public string password = "hey";

public void CreatePasswords(string keys) 
{
    if (keys == password) 
    {
        done = true;
    }
    if (keys.Length == passwordLength || done == true) 
    {
        return;
    }
    for (char c = firstchar; c <= lasrchar; c++) 
    {
        tries++;
        CreatePasswords(keys + c);
    }
}

static void Main(string[] args) 
{
    Program program = new Program();

    Console.ForegroundColor = ConsoleColor.DarkRed;
    Console.WriteLine("welcome to my brute force password cracker.");

    System.Threading.Thread.Sleep(3000);

    Console.Write("this program was created by ");
    Console.ForegroundColor = ConsoleColor.Red;
    Console.Write("Volt");
    Console.ForegroundColor = ConsoleColor.DarkRed;
    Console.WriteLine(".");

    System.Threading.Thread.Sleep(2800);

    Console.WriteLine("note that passwords found in under a second won't tell you how many passwords per second they got.");

    System.Threading.Thread.Sleep(5000);

    Console.ForegroundColor = ConsoleColor.DarkYellow;
    Console.Write("nplease enter your password > ");

    program.password = Convert.ToString(Console.ReadLine());
    program.password = program.password.ToLower();

    //Debug.Log(program.password = Convert.ToString(Console.ReadLine()));
    //Debug.Log(program.password = program.password.ToLower());

    Console.ForegroundColor = ConsoleColor.DarkRed;
    Console.WriteLine("ncracking your password...");

    Stopwatch timer = Stopwatch.StartNew();

    program.passwordLength = program.password.Length;
    program.CreatePasswords(string.Empty);
    timer.Stop();

    //Debug.Log(program.passwordLength = program.password.Length);
    //Debug.Log(program.CreatePasswords(string.Empty));

    long elapsedMs = timer.ElapsedMilliseconds;
    double elapsedTime = elapsedMs / 1000;

    if (elapsedTime > 0) 
    {
        Console.WriteLine("nnyour password has been found! here are the statistics:");
        Console.WriteLine("----------------------------------");
        Console.WriteLine("password: {0}", program.password);
        Console.WriteLine("password length: {0}", program.passwordLength);
        Console.WriteLine("tries: {0}", program.tries);

        string plural = "seconds";

        if (elapsedTime == 1) 
        {
            plural = "second";
        }
        Console.WriteLine("time to crack: {0} {1}", elapsedTime, plural);
        Console.WriteLine("passwords per second: {0}", (long)(program.tries / elapsedTime));
    }
    else 
    {
        Console.WriteLine("nnyour password has been found! here are the statistics:");
        Console.WriteLine("----------------------------------");
        Console.WriteLine("password: {0}", program.password);
        Console.WriteLine("password length: {0}", program.passwordLength);
        Console.WriteLine("tries: {0}", program.tries);
        Console.WriteLine("time to crack: {0} seconds", elapsedTime);
    }
    System.Threading.Thread.Sleep(5000);
    Console.ForegroundColor = ConsoleColor.DarkYellow;
    Console.Write("nnpress any key to close");
    Console.ReadKey();
}

Please note, this isn’t an actual brute force password cracker. I simply made this for fun.

I don’t know why I am getting this error. I am using Repl.it at school since we are using chromebooks, but I don’t think the C# would be different. I’m debugging some code just to see what it looks like in the console, but it just simply won’t work. I am just getting errors. I’m using System.Diagnostics, System.IO, and System.

I know C# pretty well, so I don’t think I’m missing anything. I believe it’s just simply a Repl.it issue.

Here is my C# code:

public char firstchar = 'a';
public char lasrchar = 'z';

public int passwordLength = 6;
public long tries = 0;

public bool done = false;

public string password = "hey";

public void CreatePasswords(string keys) 
{
    if (keys == password) 
    {
        done = true;
    }
    if (keys.Length == passwordLength || done == true) 
    {
        return;
    }
    for (char c = firstchar; c <= lasrchar; c++) 
    {
        tries++;
        CreatePasswords(keys + c);
    }
}

static void Main(string[] args) 
{
    Program program = new Program();

    Console.ForegroundColor = ConsoleColor.DarkRed;
    Console.WriteLine("welcome to my brute force password cracker.");

    System.Threading.Thread.Sleep(3000);

    Console.Write("this program was created by ");
    Console.ForegroundColor = ConsoleColor.Red;
    Console.Write("Volt");
    Console.ForegroundColor = ConsoleColor.DarkRed;
    Console.WriteLine(".");

    System.Threading.Thread.Sleep(2800);

    Console.WriteLine("note that passwords found in under a second won't tell you how many passwords per second they got.");

    System.Threading.Thread.Sleep(5000);

    Console.ForegroundColor = ConsoleColor.DarkYellow;
    Console.Write("nplease enter your password > ");

    program.password = Convert.ToString(Console.ReadLine());
    program.password = program.password.ToLower();

    //Debug.Log(program.password = Convert.ToString(Console.ReadLine()));
    //Debug.Log(program.password = program.password.ToLower());

    Console.ForegroundColor = ConsoleColor.DarkRed;
    Console.WriteLine("ncracking your password...");

    Stopwatch timer = Stopwatch.StartNew();

    program.passwordLength = program.password.Length;
    program.CreatePasswords(string.Empty);
    timer.Stop();

    //Debug.Log(program.passwordLength = program.password.Length);
    //Debug.Log(program.CreatePasswords(string.Empty));

    long elapsedMs = timer.ElapsedMilliseconds;
    double elapsedTime = elapsedMs / 1000;

    if (elapsedTime > 0) 
    {
        Console.WriteLine("nnyour password has been found! here are the statistics:");
        Console.WriteLine("----------------------------------");
        Console.WriteLine("password: {0}", program.password);
        Console.WriteLine("password length: {0}", program.passwordLength);
        Console.WriteLine("tries: {0}", program.tries);

        string plural = "seconds";

        if (elapsedTime == 1) 
        {
            plural = "second";
        }
        Console.WriteLine("time to crack: {0} {1}", elapsedTime, plural);
        Console.WriteLine("passwords per second: {0}", (long)(program.tries / elapsedTime));
    }
    else 
    {
        Console.WriteLine("nnyour password has been found! here are the statistics:");
        Console.WriteLine("----------------------------------");
        Console.WriteLine("password: {0}", program.password);
        Console.WriteLine("password length: {0}", program.passwordLength);
        Console.WriteLine("tries: {0}", program.tries);
        Console.WriteLine("time to crack: {0} seconds", elapsedTime);
    }
    System.Threading.Thread.Sleep(5000);
    Console.ForegroundColor = ConsoleColor.DarkYellow;
    Console.Write("nnpress any key to close");
    Console.ReadKey();
}

Please note, this isn’t an actual brute force password cracker. I simply made this for fun.

Понравилась статья? Поделить с друзьями:
  • Error cs0111 unity
  • Error cs0106 the modifier static is not valid for this item
  • Error cs0106 the modifier private is not valid for this item
  • Error cs0104 random is an ambiguous reference between unityengine random and system random
  • Error cs0104 debug is an ambiguous reference between unityengine debug and system diagnostics debug