По туториалу собираю 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;
}
}
}
}
I am new to Unity and C# and I want to use “AddForce” to apply force on a 3D object (sphere). I have the following C#-script that I try to run in Visual Studio 2019 (With Unity 2020.2.0b14):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script14sept : MonoBehaviour {
public float forceValue;
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponentInParent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
rb.AddForce(new Vector3(Input.GetAxis("Horizontal"),
0,
Input.GetAxis("Vertical")) * forceValue);
}
}
However, running this code results in an error:
Error CS0122 ‘Rigidbody.AddForce(Vector3)’ is inaccessible due to its protection level
Is there something wrong in the code or does it depend on another issue (e.g. using the beta version of Unity)?
Содержание
- Как исправить ошибки CS0117 и CS0122?
- Ошибка CS0117 в Unity.
- Ошибка 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: Error CS0122: `UICheckbox.mChecked’ is inaccessible due to its protection level (Read 3599 times)
I’ve just opened my project in Unity 4 and received this error, I updated NGUI to the latest version and i’m still getting the error. Here’s the script:
-
using UnityEngine;
-
using System.Collections;
-
public class LeftHandOptionScript : MonoBehaviour {
-
public UICheckbox Checkbox;
-
// Use this for initialization
-
void Start () {
-
Checkbox = GetComponent<UICheckbox>();
-
}
-
// Update is called once per frame
-
void Update () {
-
if ( Checkbox.mChecked == true){
-
PlayerPrefsX.SetBool(«Left Hand Mode», true);
-
}
-
else if ( Checkbox.mChecked == false) {
-
PlayerPrefsX.SetBool(«Left Hand Mode», false);
-
}
-
}
-
}
Can anyone help please?
Logged
Logged
Use ‘isChecked’.
Thanks, that worked
Logged
The error is this one:
«Assets/NGUI/Examples/Scripts/InventorySystem/Editor/InvDatabaseInspector.cs(45,45): error CS0122: `NGUIEditorTools.DrawBackground(UnityEngine.Texture2D, float)’ is inaccessible due to its protection level»
And the line it shows me is this one:
Rect rect = NGUIEditorTools.DrawBackground(tex, ratio);
Thanks!
—-
A friend tell me to make public Rect DrawBackground in the NGUIEditorTools.cs and now it works.
static public Rect DrawBackground (Texture2D tex, float ratio)
« Last Edit: March 21, 2013, 09:06:39 AM by jeldrez »
Logged