質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%

Q&A

解決済

1回答

1083閲覧

Unity UnityのUIテキストにPlayerScriptのHPを表示させたい

marine08

総合スコア14

0グッド

0クリップ

投稿2020/06/18 11:42

The name 'foodText' does not exist in the current context
というエラーメッセージがでています。
2Dのアクションゲームで、プレイヤーの空腹状態をUIキャンバス上にスクリプト上の数字を表示したいと思っています。
UIのスクリプト

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

public class PlayerStatusUI : MonoBehaviour
{

void Start() { foodText = this.GetComponent<Text>(); } void Update() { foodText.text = string.Format("くうふく:{0}", foodText.text); }

}

Playerのスクリプト

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

public class PlayerManager : MonoBehaviour
{
public float moveSpeed = 3f;
public Transform attackPoint;
public float attackRadius;
public LayerMask enemyLayer;
Rigidbody2D rb;
Animator animator;
int at = 1;
public AnimationClip[] animations;

private int food = 100; //現在のHP public Text foodText; void Start() { rb = GetComponent<Rigidbody2D>(); animator = GetComponent<Animator>(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Attack(); } Movement(); } void Attack() { animator.SetTrigger("IsAttack"); Collider2D[] hitEnemys = Physics2D.OverlapCircleAll(attackPoint.position, attackRadius, enemyLayer); foreach (Collider2D hitEnemy in hitEnemys) { Debug.Log(hitEnemy.gameObject.name + "に攻撃"); hitEnemy.GetComponent<EnemyManager>().OnDamage(at); } } private void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(attackPoint.position, attackRadius); } void Movement() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector2 position = transform.position; position.x = position.x + 3.0f * horizontal * Time.deltaTime; position.y = position.y + 3.0f * vertical * Time.deltaTime; transform.position = position; }

}

です。アドバイスお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

foodTextがPlayerStatusUIのどこにも定義されていません。
PlayerManagerにfoodTextがありますが、別のクラスに書いても意味がありません(※)ので、PlayerStatusUI内で定義してください。
(※:厳密には、何かで定義したクラスのインスタンスを取得しない限り使えない)

投稿2020/06/18 11:59

編集2020/06/18 22:56
fiveHundred

総合スコア9805

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

marine08

2020/06/18 22:49

ありがとうございます!^_^
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問