我正在研究2D Unity游戏,您可以在不同的角色之间切换,并在处于控制状态时和不受控制状态时将它们四处移动。例如:我有两个字符loli,另一个是pop。主角是萝莉,你可以随意移动她。但是,如果您需要将流行音乐移至某个地方,因为有一个她不认识的敌人,该怎么办?因此,玩家单击流行音乐,就像用萝莉一样移动她,然后您可以通过单击回到萝莉来重新控制萝莉。 为此,我需要让每个角色都阅读播放器控制脚本并按照其说明进行操作,并且只有在播放器点击了萝莉或流行音乐时,他们才会阅读该脚本。请注意,萝莉是默认角色,因此在游戏开始时,除非玩家单击流行音乐,否则她就是玩家控制的角色。 问题是我只知道如何在C,python和lua上执行此操作,而不是C#。那我该怎么做呢?我可以在播放器代码中制作一个方法,并告诉其他人引用它吗?
玩家代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class user : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
public int move = 5;
private int acceleration = 2;
public int Acceleration { get => acceleration; set => acceleration = value;
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.W))
{
transform.position = Vector2.up * move * Input.GetAxis("Vertical");
}
if (Input.GetKey(KeyCode.S))
{
transform.position = Vector2.down * move * Input.GetAxis("Vertical");
}
if (Input.GetKey(KeyCode.D))
{
transform.position = Vector2.right * move * Input.GetAxis("Horizontal");
}
if (Input.GetKey(KeyCode.A))
{
transform.position = Vector2.left * move * Input.GetAxis("Horizontal");
}
}
}
萝莉的密码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class loli : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
/*
* read user.cs. until another character has been selected
* then I'll do my own thing :D
* Until I get clicked on D:
*/
}
}
pop的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pop : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
/*
* if i have been clicked on,
* read user.cs.
* else, do my own thing :D
*/
}
}
答案 0 :(得分:0)
您直接要求的不是解决问题的合适方法,这是一个如何在两个GameObject之间共享常见行为的问题。
一种更好的解决方法是将user
脚本的一个实例放在Loli的GameObject
上,并将其单独的实例放在Pop的GameObject
上。然后,在user
中,添加一个布尔字段,以跟踪它是否是当前活动的字符:
public class user : MonoBehaviour
{
public bool isActiveCharacter = false;
...
在Update
中,如果您不是活动角色,请不要做任何不必要的事情
public class user : MonoBehaviour
{
...
void Update()
{
// Stuff that should happen on every frame,
// e.g., checking if this character is clicked on
if (!isActiveCharacter) return;
// Stuff that should only happen when character is selected
if(Input.GetKey(KeyCode.W))
...
然后在编辑器中,可以将Loli的isActiveCharacter
组件上的user
设置为true
,以便她是默认的活动角色。
然后,您只需要编写代码即可在单击该字符时设置适当的isActiveCharacter
,并将另一个设置为false。一种方法是给每个user
引用另一个(如果只有两个用户):
public class user : MonoBehaviour
{
public bool isActiveCharacter = false;
public user other;
...
您可能希望在编辑器中分配此引用(或使用GameObject.Find
动态查找它,这可能会很慢)。然后,在检测字符点击的代码中,设置other.isActiveCharacter = false;
。