Hi there,
I am creating a mobile endless runner type game, and wanted to install two buttons.
One for jumping and another for the player to fire projectiles.
I have created a button on Canvas, as UI, and wired up player movement script to the button.
So when the button gets pressed, player will jump.
It works, except the MissingComponentError kept showing up.
I am not sure why the script is trying to call something on Canvas when I wired player character directly to the button.
This is the script:
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Globalization;
public class dragonGoUp : MonoBehaviour
{
public float dragonJump;
private Rigidbody2D myRigidbody;
private Animator myAnim;
private Collider2D myCollider;
private float dragonHurtTime = -1;
public Text scoreText;
private float startTime;
public AudioSource jumpSfx;
public AudioSource impactSfx;
public Transform dragonProjectile;
// Start is called before the first frame update
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
myCollider = GetComponent<Collider2D>();
startTime = Time.time;
}
// Update is called once per frame
void Update()
{
//retun to title screen code for pc
/*if (Input.GetKeyDown(KeyCode.Escape))
{
SceneManager.LoadScene("Title");
}*/
if (dragonHurtTime == -1)
{
myAnim.SetFloat("vFly", myRigidbody.position.y);
print(myRigidbody.position.y);
scoreText.text = (Time.time - startTime).ToString("0.0");
}
else
{
if (Time.time > dragonHurtTime + 2)
{
SceneManager.LoadScene("protogame");
}
}
}
public void DragonMobility()
{
if (dragonHurtTime == -1)
{
myRigidbody.AddForce(transform.up * dragonJump);
jumpSfx.Play();
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.gameObject.layer == LayerMask.NameToLayer("Enemy"))
{
foreach (Spawner spawnerer in FindObjectsOfType<Spawner>())
{
spawnerer.enabled = false;
}
foreach (totheLeft totheLefter in FindObjectsOfType<totheLeft>())
{
totheLefter.enabled = false;
}
dragonHurtTime = Time.time;
myAnim.SetBool("dragonHurt", true);
myRigidbody.velocity = Vector2.zero;
myRigidbody.AddForce(transform.up * dragonJump);
myCollider.enabled = false;
impactSfx.Play();
}
}
}
When I tried attaching Rigidbody 2D component to the Canvas the error went away, just to be replaced with Animator component missing… and I doubt adding all erroneous component to the Canvas is a good idea and not sure how.
It feels like I’m missing something or not doing things in the right step, yet I have no idea what to do
(; -
Could someone please teach me what’s going on? I’m a total noob at coding…
Thank you