c# - 如何从骰子脚本中获取骰子值到石头脚本
问题描述
我想从石头脚本中的骰子脚本访问 dicevalue。所以石头可以根据骰子值移动。我在垄断上尝试这个。
骰子.cs
public class dice : MonoBehaviour
{
Rigidbody rb;
bool haslanded;
bool thrown;
Vector3 initPosition;
public int dicevalue;
public DiceSide[] diceSides;
void Start()
{
rb = GetComponent<Rigidbody>();
initPosition = transform.position;
rb.useGravity = false;
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
RollDice();
}
if(rb.IsSleeping() && !haslanded && thrown)
{
haslanded = true;
rb.useGravity = false;
rb.isKinematic = true;
SideValueCheck();
}
else if (rb.IsSleeping() && haslanded && dicevalue ==0)
{
RollAgain();
}
}
void RollDice()
{
if (!thrown && !haslanded)
{
thrown = true;
rb.useGravity = true;
rb.AddTorque(Random.Range(0, 500), Random.Range(0, 500), Random.Range(0, 500));
}
else if (thrown && haslanded)
{
Reset();
}
}
void Reset()
{
transform.position = initPosition;
thrown = false;
haslanded = false;
rb.useGravity = false;
rb.isKinematic = false;
}
void RollAgain()
{
Reset();
thrown = true;
rb.useGravity = true;
rb.AddTorque(Random.Range(0, 500), Random.Range(0, 500), Random.Range(0, 500));
}
void SideValueCheck()
{
dicevalue = 0;
foreach (DiceSide side in diceSides)
{
if(side.onGround())
{
dicevalue = side.sideValue;
Debug.Log(dicevalue + "has been rolled");
}
}
}
}
石头.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Stone : MonoBehaviour
{
public Route currentRoute;
int routePosition;
public int steps;
bool isMoving;
void Update()
{
if(Input.GetKeyDown(KeyCode.Space) && !isMoving)
{
steps = Random.Range(1, 12);
在这里,也许我可以使用 getcomponent。但它不工作。玩家(石头在压制空间上没有移动。
Debug.Log("Dice Rolled" );
StartCoroutine(Move());
}
}
IEnumerator Move()
{
if(isMoving)
{
yield break;
}
isMoving = true;
while(steps>0)
{
routePosition++;
routePosition %= currentRoute.childnodeList.Count;
Vector3 nextPos = currentRoute.childnodeList[routePosition].position;
while (MoveToNextNode(nextPos)) { yield return null; }
yield return new WaitForSeconds(0.1f);
steps--;
}
isMoving = false;
}
bool MoveToNextNode(Vector3 goal)
{
return goal != (transform.position = Vector3.MoveTowards(transform.position, goal, 8f * Time.deltaTime));
}
}
解决方案
To get value diceValue
from Dice.cs, on Stone.cs use:
FindObjectOfType<Dice>().diceValue;
FindObjectOfType will return the first instance of Dice script it can find in the scene, if there are multiple dice use FindObjectsOfType and get the object based on index. From there, you can access the public variable diceValue
using .diceValue
. (assuming that Dice.cs and Stone.cs are scripts attached to GameObjects
).
推荐阅读
- sql - XMLAGG 在结果中重复
- sockets - c++ 创建的套接字值非常大,例如 590258032 等
- xamarin - Xamarin Android 自定义 NOTICE 文件
- c++ - opengl light减少反射
- perl - Perl:如果 IPC::Run 死了,则从进程中检索输出
- php - PHP,从关联多维数组中的特定 $key 中获取 $value
- sql - 在一个视图中运行两个选择语句?
- sql - Acumatica GI 库存周转率
- xamarin.forms - Xamarin.Forms v3 中的 MasterDetail + 从右到左
- sql-server - Windows 任务计划程序和对 MSSQL 数据库的权限