Reputation: 11
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
bool canJump;
public class PlayerController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("left"))
{
gameObject.transform.Translate(-50f * Time.deltaTime, 0, 0);
}
if (Input.GetKey("right"))
{
gameObject.transform.Translate(50f * Time.deltaTime, 0, 0);
}
ManageJump();
}
void ManageJump()
{
if(gameObject.transform.position.y <= 0)
{
canJump = true;
}
if (Input.GetKey("up") && canJump && gameObject.transform.position.y < 10)
{
gameObject.transform.Translate(0, 50f * Time.deltaTime, 0);
}
else
{
canJump = false;
if (gameObject.transform.position.y > 0)
{
gameObject.transform.Translate(0, -50f * Time.deltaTime, 0);
}
}
}
I dont find the error in the code.
I get the following errors:
Assets\scripts\PlayerController.cs(35,13): error CS8801: Cannot use local variable or local function 'canJump' declared in a top-level statement in this context.
Assets\scripts\PlayerController.cs(38,35): error CS8801: Cannot use local variable or local function 'canJump' declared in a top-level statement in this context.
Assets\scripts\PlayerController.cs(45,13): error CS8801: Cannot use local variable or local function 'canJump' declared in a top-level statement in this context.
Assets\scripts\PlayerController.cs(38,35): error CS0165: Use of unassigned local variable 'canJump'
Upvotes: 1
Views: 407
Reputation: 6327
your variable is in the wrong location
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// this needs to go here
bool canJump;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("left"))
{
gameObject.transform.Translate(-50f * Time.deltaTime, 0, 0);
}
if (Input.GetKey("right"))
{
gameObject.transform.Translate(50f * Time.deltaTime, 0, 0);
}
ManageJump();
}
void ManageJump()
{
if(gameObject.transform.position.y <= 0)
{
canJump = true;
}
if (Input.GetKey("up") && canJump && gameObject.transform.position.y < 10)
{
gameObject.transform.Translate(0, 50f * Time.deltaTime, 0);
}
else
{
canJump = false;
if (gameObject.transform.position.y > 0)
{
gameObject.transform.Translate(0, -50f * Time.deltaTime, 0);
}
}
}
}
Upvotes: 2