乱码是中文注释。
通用
音乐播放脚本SceneMusicPlayer.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneMusicPlayer : MonoBehaviour
{
public string targetSceneName = "SampleScene";
private static SceneMusicPlayer _instance;
void Awake()
{
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(gameObject);
SceneManager.sceneLoaded += OnSceneLoaded;
}
else
{
Destroy(gameObject);
}
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
AudioSource audioSource = GetComponent<AudioSource>();
if (scene.name == targetSceneName)
{
if (!audioSource.isPlaying)
{
audioSource.Play();
}
}
else
{
if (audioSource.isPlaying)
{
audioSource.Stop();
}
}
}
void OnDestroy()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
}
开幕视频OpeningVideoController.cs
using UnityEngine;
using UnityEngine.Video;
using UnityEngine.SceneManagement;
public class OpeningVideoPlayer : MonoBehaviour
{
[SerializeField] private VideoPlayer videoPlayer;
[SerializeField] private string nextScene = "GameScene";
private float timer = 0f;
private bool canSkip = false;
void Start()
{
videoPlayer = GetComponent<VideoPlayer>();
videoPlayer.url = System.IO.Path.Combine(Application.streamingAssetsPath, "Opening.mp4");
videoPlayer.Play();
videoPlayer.loopPointReached += EndReached;
}
void Update()
{
if (!canSkip)
{
timer += Time.deltaTime;
if (timer >= 3f) canSkip = true;
}
if (canSkip && Input.anyKeyDown)
{
LoadNextScene();
}
}
private void EndReached(VideoPlayer vp)
{
LoadNextScene();
}
private void LoadNextScene()
{
SceneManager.LoadScene(nextScene);
}
}
电脑端脚本
移动脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayMovement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll;
private SpriteRenderer sprite;
private Animator anim;
[SerializeField] private LayerMask jumpableGround;
private float dirX = 0f;
[SerializeField] private float movespeed = 7;
[SerializeField] private float jumpforce = 12;
public int StateSpeedUp = 0;
private enum MovementState { idle, running, jumping, falling }
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
coll = GetComponent<BoxCollider2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
IsSpeedUp();
Jump();
Horizontal_movement();
UpdateAnimationState();
}
void Jump() //��Ծ
{
if ((Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.Space)) && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpforce);
}
}
void Horizontal_movement() //ˮƽ�ƶ�
{
if (Input.GetKey(KeyCode.LeftShift))
{
rb.velocity = new Vector2(dirX * 11, rb.velocity.y);
}
else
{
rb.velocity = new Vector2(dirX * movespeed, rb.velocity.y);
}
}
void UpdateAnimationState() //���¶���
{
MovementState state;
//ˮƽ�˶�����
if (dirX > 0f)
{
state = MovementState.running;
sprite.flipX = false; //ˮƽ��ת
}
else if (dirX < 0f)
{
state = MovementState.running;
sprite.flipX = true;
}
else
{
state = MovementState.idle;
}
//��ֱ��Ծ����
if (rb.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rb.velocity.y < -.1f)
{
state = MovementState.falling;
}
anim.SetInteger("state", (int)state);
}
private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
public void IsSpeedUp() //����ģʽ�����������F�����
{
if (Input.GetKeyDown(KeyCode.F) && StateSpeedUp < 3)
{
StateSpeedUp += 1;
}
if (StateSpeedUp == 3)
{
movespeed = 20;
if (Input.GetKeyDown(KeyCode.R)) // �ָ�
{
movespeed = 7;
StateSpeedUp = 0;
}
}
else
{
movespeed = 7;
}
}
}
提示板脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Sign : MonoBehaviour
{
private GameObject dialogBox; // ָ��TipBoardͼƬ
private TextMeshProUGUI dialogBoxText; // ָ��TipBoardText����
[TextArea] public string signText;
private bool isPlayerInSign;
private int toggleState = 0;
void Start()
{
// ����Sign_Canvas�µ�TipBoard����
Transform signCanvas = GameObject.Find("Sign_Canvas").transform;
dialogBox = signCanvas.Find("TipBoard").gameObject;
// ��TipBoard�²���TipBoardText����ȡ��TextMeshProUGUI���
dialogBoxText = dialogBox.transform.Find("TipBoardText").GetComponent<TextMeshProUGUI>();
dialogBox.SetActive(false);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E) && isPlayerInSign)
{
toggleState++;
bool isActive = (toggleState % 2 != 0);
dialogBox.SetActive(isActive);
if (isActive)
{
dialogBoxText.text = signText;
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
isPlayerInSign = true;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
isPlayerInSign = false;
dialogBox.SetActive(false);
toggleState = 0;
}
}
}
手机端脚本
按钮控件
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MobileInputHandler : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public PlayerMovement playerMovement;
public string buttonType;
private Image buttonImage;
private Color normalColor = new Color(1, 1, 1, 0.7f);
private Color pressedColor = new Color(0.8f, 0.8f, 0.8f, 1f);
void Start()
{
buttonImage = GetComponent<Image>();
if (buttonImage != null)
{
buttonImage.color = normalColor;
}
else
{
Debug.LogWarning("Image component not found on button: " + gameObject.name);
}
// 自动查找玩家对象
if (playerMovement == null)
{
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player != null)
{
playerMovement = player.GetComponent<PlayerMovement>();
if (playerMovement == null)
{
Debug.LogError("PlayerMovement component not found on player!");
}
}
else
{
Debug.LogError("Player object not found in scene!");
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
if (playerMovement == null)
{
Debug.LogWarning("PlayerMovement reference not set on button: " + gameObject.name);
return;
}
if (buttonImage != null)
{
buttonImage.color = pressedColor;
}
switch (buttonType)
{
case "Left":
playerMovement.SetHorizontalInput(-1);
Debug.Log("Left button pressed");
break;
case "Right":
playerMovement.SetHorizontalInput(1);
Debug.Log("Right button pressed");
break;
case "Jump":
playerMovement.JumpButtonPressed();
Debug.Log("Jump button pressed");
break;
case "Interact":
playerMovement.InteractButtonPressed();
Debug.Log("Interact button pressed");
break;
default:
Debug.LogWarning("Unknown button type: " + buttonType);
break;
}
}
public void OnPointerUp(PointerEventData eventData)
{
if (buttonImage != null)
{
buttonImage.color = normalColor;
}
if (playerMovement == null)
return;
if (buttonType == "Left" || buttonType == "Right")
{
playerMovement.SetHorizontalInput(0);
Debug.Log("Movement button released");
}
}
}
角色交互
using UnityEngine;
public class PlayerInteract : MonoBehaviour
{
public Sign currentSign;
private void OnDrawGizmos()
{
if (currentSign != null)
{
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, currentSign.transform.position);
}
}
public void SetCurrentSign(Sign sign)
{
if (currentSign != sign)
{
Debug.Log($"Setting current sign: {sign?.name ?? "null"}");
currentSign = sign;
}
}
public void ClearCurrentSign()
{
if (currentSign != null)
{
Debug.Log($"Clearing current sign: {currentSign.name}");
currentSign = null;
}
}
public void AttemptInteraction()
{
Debug.Log("Attempting interaction");
if (currentSign != null)
{
Debug.Log($"Interacting with: {currentSign.name}");
currentSign.ToggleDialog();
}
else
{
Debug.LogWarning("No current sign to interact with!");
}
}
}
角色移动
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll;
private SpriteRenderer sprite;
private Animator anim;
[SerializeField] private LayerMask jumpableGround;
private float dirX = 0f;
[SerializeField] private float movespeed = 7;
[SerializeField] private float jumpforce = 12;
public int StateSpeedUp = 0;
private enum MovementState { idle, running, jumping, falling }
// 移动端新增变量
private bool jumpRequested = false;
private bool interactRequested = false;
private PlayerInteract playerInteract;
void Start()
{
rb = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
coll = GetComponent<BoxCollider2D>();
anim = GetComponent<Animator>();
// 确保PlayerInteract组件存在
playerInteract = GetComponent<PlayerInteract>();
if (playerInteract == null)
{
playerInteract = gameObject.AddComponent<PlayerInteract>();
Debug.Log("PlayerInteract component added to player");
}
}
void Update()
{
Jump();
HorizontalMovement();
UpdateAnimationState();
HandleInteraction();
}
private void HandleInteraction()
{
if (interactRequested)
{
interactRequested = false;
if (playerInteract != null)
{
playerInteract.AttemptInteraction();
}
else
{
Debug.LogWarning("PlayerInteract component not found!");
}
}
}
public void SetHorizontalInput(float input)
{
dirX = input;
}
public void JumpButtonPressed()
{
if (IsGrounded())
{
jumpRequested = true;
}
}
void Jump()
{
if (jumpRequested)
{
rb.velocity = new Vector2(rb.velocity.x, jumpforce);
jumpRequested = false;
}
}
void HorizontalMovement()
{
rb.velocity = new Vector2(dirX * movespeed, rb.velocity.y);
}
void UpdateAnimationState()
{
MovementState state;
if (dirX > 0f)
{
state = MovementState.running;
sprite.flipX = false;
}
else if (dirX < 0f)
{
state = MovementState.running;
sprite.flipX = true;
}
else
{
state = MovementState.idle;
}
if (rb.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rb.velocity.y < -.1f)
{
state = MovementState.falling;
}
anim.SetInteger("state", (int)state);
}
private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
public void InteractButtonPressed()
{
interactRequested = true;
Debug.Log("Interact button pressed");
}
}
提示板
// Sign.cs 修改退出触发器逻辑
using UnityEngine;
using TMPro;
public class Sign : MonoBehaviour
{
private GameObject dialogBox;
private TextMeshProUGUI dialogBoxText;
[TextArea] public string signText;
private bool isPlayerInSign;
private int toggleState = 0;
public PlayerInteract playerInteractRef;
void Start()
{
Transform signCanvas = GameObject.Find("Sign_Canvas").transform;
dialogBox = signCanvas.Find("TipBoard").gameObject;
dialogBoxText = dialogBox.transform.Find("TipBoardText").GetComponent<TextMeshProUGUI>();
dialogBox.SetActive(false);
}
public void ToggleDialog()
{
if (!isPlayerInSign)
{
Debug.LogWarning("Cannot toggle dialog - player not in sign");
return;
}
toggleState++;
bool isActive = (toggleState % 2 != 0);
dialogBox.SetActive(isActive);
if (isActive)
{
dialogBoxText.text = signText;
Debug.Log("Dialog shown: " + signText);
}
else
{
Debug.Log("Dialog hidden");
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player entered sign trigger: " + gameObject.name);
isPlayerInSign = true;
playerInteractRef = other.GetComponent<PlayerInteract>();
if (playerInteractRef != null)
{
playerInteractRef.SetCurrentSign(this);
}
else
{
Debug.LogError("PlayerInteract component not found on player!");
}
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player exited sign trigger: " + gameObject.name);
isPlayerInSign = false;
if (playerInteractRef != null)
{
// 关键修改:只清除自己设置的标记
if (playerInteractRef.currentSign == this)
{
playerInteractRef.ClearCurrentSign();
}
}
dialogBox.SetActive(false);
toggleState = 0;
}
}
}
文档信息
- 本文作者:ovuleseed
- 本文链接:https://ovule-seed.github.io/2025/07/29/%E6%BA%90%E7%A0%81/
- 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
ovule-seed.github.io