Когда я подхожу к ящику и нажимаю английскую букву E ничего не происходит, но
когда в Unity я переключаю переменою Hold на true то улетаю куда-то.
А вот ошибка когда я просто стою и переменою Hold на true:
NullReferenceException: Object reference not set to an instance of an object
BoxHold.Update () (at Assets/Scrips/BoxHold.cs:44)
Вот то что в Unity.
Код скрипта для подбирания ящиков:
public class BoxHold : MonoBehaviour
{
public bool hold;
public float distanse = 3f;
RaycastHit2D hit;
public Transform holdPoint;
public float throwObject = 5f;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (!hold)
{
Physics2D.queriesStartInColliders = false;
hit = Physics2D.Raycast(transform.position, Vector2.right * transform.localScale.x, distanse);
if (hit.collider != null && hit.collider.tag == "box")
{
hold = true;
}
}
else
{
hold = false;
if (hit.collider.gameObject.GetComponent<Rigidbody2D>() != null)
{
hit.collider.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(transform.localScale.x, 1) * throwObject;
}
}
}
if (hold)
{
hit.collider.gameObject.transform.position = holdPoint.position;
}
}
private void onDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position, transform.position + Vector3.right * transform.localScale.x * distanse);
}
}
Код скрипта игрока:
public class PlayerControl : MonoBehaviour
{
public float move = 5f;
public GameObject obj;
public float jumpForse;
public bool isGrounded, isBox;
public Transform groundCheck;
public float groundRadius;
public LayerMask whatIsGround, whatIsBox;
private bool ifRight = true;
private float moveInput;
private Rigidbody2D rb;
private int extraJump;
public int extraJumpValue;
private void Start()
{
extraJump = extraJumpValue;
print("hello!");
rb = GetComponent<Rigidbody2D>();
}
void Flip()
{
ifRight = !ifRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
isBox = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsBox);
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * move, rb.velocity.y);
if (ifRight == false && moveInput > 0)
{
Flip();
}
else if (ifRight == true && moveInput < 0)
{
Flip();
}
}
private void Update()
{
if (isGrounded == true || isBox == true)
{
extraJump = extraJumpValue;
}
if (Input.GetKeyDown(KeyCode.W) && extraJump > 0)
{
rb.velocity = Vector2.up * jumpForse;
extraJump--;
}
else if (Input.GetKeyDown(KeyCode.W) && extraJump == 0 && isGrounded == true || Input.GetKeyDown(KeyCode.W) && extraJump == 0 && isBox == true)
{
rb.velocity = Vector2.up * jumpForse;
}
}
}