using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Player : MonoBehaviour
{
[SerializeField] private DialogueUI dialogueUI;
public Vector3 raypositionup = new Vector3(5, 0, 0);
public Vector3 raypositiondown = new Vector3(5, 0, 0);
private float MoveSpeed = 7f;
public Animator animator;
public DialogueUI DialogueUI => dialogueUI;
public Interactable Interactable { get; set; }
bool move = false;
bool movefoward = false;
public Rigidbody2D rb;
Vector2 movement;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (DialogueUI.IsOpen) return;
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown(KeyCode.W))
{
move = true;
movefoward = false;
animator.SetBool("Lookingfoward", true);
}
if (Input.GetKeyDown(KeyCode.S))
{
movefoward = true;
move = false;
animator.SetBool("Lookingfoward", false);
}
if (Input.GetKey(KeyCode.LeftShift))
{
MoveSpeed = 10f;
}
else
{
MoveSpeed = 7f;
}
if (Input.GetKeyDown(KeyCode.Return))
{
if (Interactable != null)
{
Interactable.Interact(this);
}
}
if (move == true)
{
if (Input.GetKey(KeyCode.E))
{
Debug.DrawRay(transform.position + raypositionup, transform.up * 2f, Color.red);
RaycastHit2D hit = Physics2D.Raycast(transform.position + raypositionup , transform.up, 2f);
if (hit.collider.CompareTag("Object"))
{
Debug.Log("Poop");
hit.transform.GetComponent<SpriteRenderer>().color = Color.red;
}
if (hit.collider == null)
{
return;
}
}
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * MoveSpeed * Time.fixedDeltaTime);
}
}
Ive tried several different fixes and none seem to work, such as another if statement, else statements, and even reworking the entire raycast system. If anyone knows a solution that would be just great. Also, any criticism on my code is okay and endorsed, im new to coding and want any opportunity I can get to clean up my code as best as possible.
You have code for return if collider is null, but not catch if null on compare:
if (hit.collider == null)
{
return;
}
elseif (hit.collider.CompareTag("Object")) //No catched if null
{
Debug.Log("Poop");
hit.transform.GetComponent<SpriteRenderer>().color = Color.red;
}