How to go back to script after starting Coroutine? - c#

I currently have a script that allows the player to pick up an item and plays an animation. I have a coroutine to wait 1 second before locking the game object to the player's hand. My problem is that my code for dropping the item and throwing it no longer functions. Is there a workaround to solve this problem?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUp : MonoBehaviour
{
bool isgrounded = true;
public Animator animator;
public GameObject Player;
public Rigidbody rb;
public bool inrange;
public int number = 1;
public Transform theDest;
public float thrust = 1.0f;
public float upthrust = 1.0f;
void start()
{
rb = GetComponent<Rigidbody>();
inrange = false;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "Player")
{
inrange = true;
}
}
private void OnTriggerExit(Collider other)
{
inrange = false;
}
public void Update()
{
bool isPickUp = animator.GetBool("isPickUp");
bool pickuppressed = Input.GetKey("e");
if (isgrounded == true)
{
if (pickuppressed && !isPickUp && inrange==true)
{
animator.SetBool("isPickUp", true);
}
if (!pickuppressed && isPickUp || inrange == false)
{
animator.SetBool("isPickUp", false);
}
if (Input.GetKeyUp(KeyCode.E) && (number % 2) == 1 && inrange == true )
{
StartCoroutine(waiter());
number = number + 1;
}
else if (Input.GetKeyUp(KeyCode.E) && (number % 2) == 0 && inrange == true)
{
GetComponent<Rigidbody>().isKinematic = false;
GetComponent<BoxCollider>().enabled = true;
this.transform.parent = null;
GetComponent<Rigidbody>().useGravity = true;
number = number - 1;
}
else if (Input.GetKey(KeyCode.G) && (number % 2) == 0 && inrange == true)
{
GetComponent<Rigidbody>().isKinematic = false;
GetComponent<BoxCollider>().enabled = true;
this.transform.parent = null;
GetComponent<Rigidbody>().useGravity = true;
number = number - 1;
rb.AddForce(Player.transform.forward * thrust);
rb.AddForce(Player.transform.up * upthrust);
}
}
void OnCollisionEnter(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = true;
}
}
//consider when character is jumping .. it will exit collision.
void OnCollisionExit(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = false;
}
}
IEnumerator waiter()
{
yield return new WaitForSeconds(1);
GetComponent<BoxCollider>().enabled = false;
GetComponent<Rigidbody>().useGravity = false;
GetComponent<Rigidbody>().isKinematic = true;
this.transform.position = theDest.position;
this.transform.parent = GameObject.Find("Destination").transform;
}
}
}
Let me know if more information is needed (still new to stack overflow)

Forget about the coroutine and use Time.time to save the time of pickup to a class variable. Then add comparison to the other if branches such as Time.time > pickupTime + 1f.

Related

Unity 2d Character moves and jumps to specific positions with UI buttons

In a simple 2d project in which my player can move to the right and left on x and can also jump to the right and left in height with two other buttons. The problem is, that the player is not supposed to move freely. By pressing one of the buttons the player should only go to the next specific point, so that the player always stops at six different positions on x (while on y he is free and as high as the platform he is currently standing on). To be able to jump realistically, the player must have gravity and a collider to be able to land on the platforms (and move single platforms horizontal).
Thanks to the tutorial which #TEEBQNE linked in the comments I could finally realise this with Unitys Rigidbody2D and the following script. The problem is that the gravity is now behaving strangely. The player only moves down very slowly and in the process pushes Gameobjects underneath it through others. The player has a Dynamic Rigidbody2D with a gravity scale of 2 and a capsule collider 2d. Is that a problem with the script or with the components in the players inspector?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movePlayer : MonoBehaviour
{
public GameObject posChecker1;
public GameObject posChecker2;
public GameObject posChecker3;
public GameObject posChecker4;
public GameObject posChecker5;
public GameObject posChecker6;
public bool go; //Player is allowed to move
public bool grounded; //Player is allowed to jump
public string moveDirection;
public float horizVel = 0; //Movement along x
public float verticVel = 0; //Jump
public int laneNum = 3; //Player starts on lane 3!!
public bool rightButtonMove = false;//
public bool leftButtonMove = false;//
public bool rightButtonJump = false;//
public bool leftButtonJump = false;//
//Animation
private SpriteRenderer spriteRenderer;
private Animator animator;
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
posChecker1.SetActive(true);//GameObject.Find("PositionChecker1").SetActive(true);
posChecker2.SetActive(true);
posChecker3.SetActive(true); //Player start on lane 3!!
posChecker4.SetActive(true);
posChecker5.SetActive(true);
posChecker6.SetActive(true);
laneNum = 3;
go = true;
}
// Update is called once per frame
void Update()
{
//Raycast
int playerMask = LayerMask.GetMask("PositionChecker");// !!!
Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.up) * 50f, Color.green);
RaycastHit2D hitCheck = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 50f, playerMask);
//Only the checker objects in the rows next to the player are active
if (laneNum == 1)
{
posChecker1.SetActive(false);
posChecker2.SetActive(true);
}
else if (laneNum == 2)
{
posChecker1.SetActive(true);
posChecker2.SetActive(false);
posChecker3.SetActive(true);
}
else if (laneNum == 3)
{
posChecker2.SetActive(true);
posChecker3.SetActive(false);
posChecker4.SetActive(true);
}
else if (laneNum == 4)
{
posChecker3.SetActive(true);
posChecker4.SetActive(false);
posChecker5.SetActive(true);
}
else if (laneNum == 5)
{
posChecker4.SetActive(true);
posChecker5.SetActive(false);
posChecker6.SetActive(true);
}
else if (laneNum == 6)
{
posChecker5.SetActive(true);
posChecker6.SetActive(false);
}
//Movement
GetComponent<Rigidbody2D>().velocity = new Vector3(horizVel, verticVel, 0);
//Raycast
if (hitCheck)
{
if (moveDirection == "l" && horizVel != 0)
{
laneNum -= 1;
}
if (moveDirection == "r" && horizVel != 0)
{
laneNum += 1;
}
go = true;
horizVel = 0;
verticVel = 0;
grounded = true;
}
if (horizVel == 0)
moveDirection = "";
//Animation
bool flipSprite = (spriteRenderer.flipX ? (horizVel > 0.01f) : (horizVel < 0.01f));
if (flipSprite)
{
spriteRenderer.flipX = !spriteRenderer.flipX;
}
animator.SetBool("grounded", grounded); // -->Jump
animator.SetFloat("velocityX", Mathf.Abs(horizVel));
}
//Button Input
public void RightButton() //
{
if (laneNum < 6 && go)
{
moveDirection = "r";
go = false;
horizVel = 4;
}
}
public void LeftButton()//
{
if (laneNum > 1 && go)
{
moveDirection = "l";
go = false;
horizVel = -4;
}
}
public void RightJump()//
{
if (laneNum < 6 && grounded && go)
{
moveDirection = "r";
horizVel = 4;
verticVel = 7;
go = false;
grounded = false;
}
}
public void LeftJump()//
{
if (laneNum > 1 && grounded && go)
{
moveDirection = "l";
horizVel = -4;
verticVel = 7;
go = false;
grounded = false;
}
}
}
Glad I was able to help in some way and that you figured out your issue!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movePlayer : MonoBehaviour
{
//Player Position x
public GameObject posChecker1;
public GameObject posChecker2;
public GameObject posChecker3;
public GameObject posChecker4;
public GameObject posChecker5;
public GameObject posChecker6;
public int laneNum = 3; //Player starts on lane 3!!
//Player Position y
public float yPos1;
public float yPos2;
public Transform player;
//Movement Variables
public bool go; //Player is allowed to move
public bool grounded; //Player is allowed to jump
public string moveDirection;
public float horizVel = 0; //Movement along x
public float verticVel = 0; //Jump
//Animation
private SpriteRenderer spriteRenderer;
private Animator animator;
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
posChecker1.SetActive(true);//GameObject.Find("PositionChecker1").SetActive(true);
posChecker2.SetActive(true);
posChecker3.SetActive(true); //Player start on lane 3!!
posChecker4.SetActive(true);
posChecker5.SetActive(true);
posChecker6.SetActive(true);
laneNum = 3;
go = true;
}
// Update is called once per frame
void Update()
{
//Raycast
int playerMask = LayerMask.GetMask("PositionChecker");// !!!
Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.up) * 50f, Color.green);
RaycastHit2D hitCheck = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 50f, playerMask);
//Only the checker objects in the rows next to the player are active
if (laneNum == 1)
{
posChecker1.SetActive(false);
posChecker2.SetActive(true);
}
else if (laneNum == 2)
{
posChecker1.SetActive(true);
posChecker2.SetActive(false);
posChecker3.SetActive(true);
}
else if (laneNum == 3)
{
posChecker2.SetActive(true);
posChecker3.SetActive(false);
posChecker4.SetActive(true);
}
else if (laneNum == 4)
{
posChecker3.SetActive(true);
posChecker4.SetActive(false);
posChecker5.SetActive(true);
}
else if (laneNum == 5)
{
posChecker4.SetActive(true);
posChecker5.SetActive(false);
posChecker6.SetActive(true);
}
else if (laneNum == 6)
{
posChecker5.SetActive(true);
posChecker6.SetActive(false);
}
//Movement
if (grounded)
{
verticVel = GetComponent<Rigidbody2D>().velocity.y;
}
GetComponent<Rigidbody2D>().velocity = new Vector3(horizVel, /*GetComponent<Rigidbody2D>().velocity.y*/verticVel, 0);
//Jump
yPos2 = player.transform.position.y;
if ((yPos2 - 2) >= yPos1 && !grounded)
{
if (moveDirection == "l")
horizVel = -4;
if (moveDirection == "r")
horizVel = 4;
verticVel = verticVel * 0.95f;
}
//Raycast
if (hitCheck)
{
if (moveDirection == "l" && horizVel != 0)
{
laneNum -= 1;
}
if (moveDirection == "r" && horizVel != 0)
{
laneNum += 1;
}
go = true;
horizVel = 0;
verticVel = 0;
grounded = true;
}
if (horizVel == 0 && grounded)
moveDirection = "";
//Animation
bool flipSprite = (spriteRenderer.flipX ? (horizVel > 0.01f) : (horizVel < 0.01f));
if (flipSprite)
{
spriteRenderer.flipX = !spriteRenderer.flipX;
}
animator.SetBool("grounded", grounded); // -->Jump
animator.SetFloat("velocityX", Mathf.Abs(horizVel));
}
//Button Input
public void RightButton() //
{
if (laneNum < 6 && go)
{
moveDirection = "r";
go = false;
horizVel = 4;
}
}
public void LeftButton()//
{
if (laneNum > 1 && go)
{
moveDirection = "l";
go = false;
horizVel = -4;
}
}
public void RightJump()//
{
if (laneNum < 6 && grounded && go)
{
moveDirection = "r";
verticVel = 5;
go = false;
grounded = false;
//
yPos1 = player.transform.position.y;
Debug.Log(yPos1);
//
}
}
public void LeftJump()//
{
if (laneNum > 1 && grounded && go)
{
moveDirection = "l";
verticVel = 5;
go = false;
grounded = false;
//
yPos1 = player.transform.position.y;
Debug.Log(yPos1);
//
}
}
}

How and where in the code should I use the loop bool flag to decide if to loop or to make once movement between the waypoints?

The goal is to be able to decide if to loop or to move only once between the waypoints.
I added the loop bool flag for that.
Added the most details I can.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.AI;
public class Move : MonoBehaviour
{
public Transform[] targets;
public LineRenderer lineRenderer;
public float speed;
public bool go = false;
public bool countOrigPosAsWaypoint = true;
public bool startFromFirstPositionOnStart = false;
public bool goForward = true;
public bool loop = true;
private List<Vector3> pos = new List<Vector3>();
private List<Vector3> positions = new List<Vector3>();
private int index = 0;
private List<GameObject> objectsToMoveCopy = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
if (lineRenderer != null)
{
pos = GetLinePointsInWorldSpace();
}
else
{
if (countOrigPosAsWaypoint == true)
{
pos.Add(transform.position);
}
for (int i = 0; i < targets.Length; i++)
{
pos.Add(targets[i].position);
}
}
if (startFromFirstPositionOnStart == true)
{
transform.position = pos[index];
}
if (pos.Count <= 1)
{
Debug.LogWarning("Targets list count must be more then 1");
}
}
List<Vector3> GetLinePointsInWorldSpace()
{
positions = new Vector3[lineRenderer.positionCount].ToList();
//Get the positions which are shown in the inspector
lineRenderer.GetPositions(positions.ToArray());
//the points returned are in world space
return positions;
}
// Update is called once per frame
void Update()
{
if (go == true && pos.Count > 1)
{
Moving();
}
}
void Moving()
{
Vector3 newPos = transform.position;
float distanceToTravel = speed * Time.deltaTime;
bool stillTraveling = true;
while (stillTraveling)
{
Vector3 oldPos = newPos;
newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
distanceToTravel -= Vector3.Distance(newPos, oldPos);
if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
{
// when you hit a waypoint:
if (goForward)
{
bool atLastOne = index >= pos.Count - 1;
if (!atLastOne) index++;
else { index--; goForward = false; }
}
else
{ // going backwards:
bool atFirstOne = index <= 0;
if (!atFirstOne) index--;
else { index++; goForward = true; }
}
}
else
{
stillTraveling = false;
}
}
transform.position = newPos;
}
}
If true make a loop between the waypoints either backward or forward and if false just move forward or backward once and stop the last/first waypoint.
I'ld say e.g. at
if (!atLastOne)
{
index++;
}
else if(!loop)
{
stillTraveling = false;
}
else
{
index--;
goForward = false;
}
and accordingly
if (!atFirstOne)
{
index--;
}
else if(!loop)
{
stillTraveling = false;
}
else
{
index++;
goForward = true;
}
And probably remove the current
else
{
stillTraveling = false;
}
as it will be the case most of the time between the points.
In general though: Currently this will all happen in one single frame without any animation... This should probably rather happen in a Coroutine or only do one step at a time .. not in a while loop at all.

Prefabs of mobs in the game on Unity do not go on the phone

There was a very interesting error with game characters, on the first level they walk quietly and everything is OK, and on the second they go only in the editor, and after compilation they are no longer there. Ai navigation exists. The character must find ... by the tag maybe he is on stage. What could be the problem? error only at the second level and only after assembly
mob script(They do not go, they do not attack if you approach. So either they don’t see or an error in the script on the phone occurs)
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
public class EmenScript: MonoBehaviour
{
public NavMeshAgent agent;
public Animator animator;
public GameObject zombieObject;
private Transform player;
private float curr_time;
private int xp = 100;
void Start()
{
player = GameObject.FindGameObjectsWithTag("Player")[0].transform;
StartCoroutine(findPath());
StartCoroutine(playerDetected());
curr_time = 0f;
}
public void damage()
{
if(xp == 0)
{
gameObject.transform.Find("Xp/Cube/").gameObject.active = false;
StopAllCoroutines();
agent.enabled = false;
animator.SetTrigger("death");
Destroy(zombieObject, 30f);
} else {
xp = xp > 15 ? xp - 15 : 0;
Transform xpp = gameObject.transform.Find("Xp/Cube/XpLine").transform;
xpp.localScale = new Vector3(xpp.localScale.x, xpp.localScale.y, xp / 100f);
xpp.localPosition = new Vector3(xpp.localPosition.x, xpp.localPosition.y, (0.97f - xpp.localScale.z) / 2);
}
}
public void damageFull()
{
gameObject.transform.Find("Xp/Cube").gameObject.active = false;
StopAllCoroutines();
agent.enabled = false;
animator.SetTrigger("death");
Destroy(zombieObject, 30f);
}
IEnumerator playerDetected()
{
while(true)
{
if(player == null)
{
break;
}
if(player.GetComponent<UserController>().xp <= 0)
{
agent.GetComponent<NavMeshAgent>().isStopped = true;
animator.SetBool("walk", false);
}
if(Vector3.Distance(transform.position, player.position) < 1.2f)
{
animator.SetTrigger("attack");
curr_time -= Time.deltaTime;
if(curr_time <= 0)
{
if(player.GetComponent<UserController>().xp - 25 > 0)
{
player.GetComponent<UserController>().xp -= 25;
}
else
{
player.GetComponent<UserController>().xp = 0;
}
curr_time = 0.5f;
}
}
yield return new WaitForSeconds(.3f);
}
}
IEnumerator findPath()
{
while(true)
{
if(player.GetComponent<UserController>().xp > 0)
{
if(Vector3.Distance(transform.position, player.position) < 40f)
{
animator.SetBool("walk", true);
if(player && agent.isActiveAndEnabled)
{
agent.GetComponent<NavMeshAgent>().isStopped = false;
agent.SetDestination(player.position);
}
} else {
agent.GetComponent<NavMeshAgent>().isStopped = true;
animator.SetBool("walk", false);
}
}
yield return new WaitForSeconds(0.2f);
}
}
}
I think error must be about scene change but I need to see script and lvl's.

Why transform.eulerAngles doesn't rotate my player?

i have a little problem with this game i'm working in, the problem is that the player object isn't rotating with the code i'm using, and it used to work before, idk why, it was working well and i tested several times it's very simple here is the code.
Edit. I just posted the all code of the controller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody2D rb;
public float speed;
public float runSpeed;
public float jumpForce;
private float moveInput;
private Vector3 rotation;
public bool isGrounded;
private bool isAlsoTrampoline;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
private Animator animator;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private int cState = 1;
private int capsState = 1;
public bool isWalking;
public bool isRunning;
public bool isCrunching;
public bool isSliding;
public bool isGraping;
public Vector3 climbPos;
private PortalDetector portalName;
private Transform otherPortal;
private int colorPortal = 0;
private GameObject otherPortalPos;
private Vector2 currentY,lastY;
private AudioSource audioStep;
private bool amFalling;
public void Step()
{
audioStep.Play();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Trampoline")
{
isAlsoTrampoline = true;
}
if (collision.tag == "Ledge")
{
Debug.Log("Puedo Trepar esto!!??? ");
if (!isGrounded)
{
isGraping = true;
rb.gravityScale = 0;
rb.velocity = new Vector3(0,0,0);
animator.SetBool("isLedge", true);
climbPos = GetComponent<Transform>().position;
Debug.Log("Trepado!!!!!:DDDDD");
}
}
if (collision.tag == "BluePortal")
{
colorPortal = 1;
}
else if (collision.tag == "OrangePortal")
{
colorPortal = 2;
}
if (collision.tag == "Transporter")
{
if (colorPortal == 1)
{
otherPortal = collision.gameObject.transform.GetChild(3);
}
if (colorPortal == 2)
{
otherPortal = collision.gameObject.transform.GetChild(2);
}
otherPortalPos = otherPortal.transform.gameObject;
transform.position = new Vector3(otherPortalPos.transform.position.x, otherPortalPos.transform.position.y, transform.position.z);
rb.velocity = new Vector3(0, 0, 0);
}
}
void BackToIdle()
{
GetComponent<Rigidbody2D>().velocity = new Vector3(climbPos.x+5,climbPos.y,climbPos.z);
GetComponent<Rigidbody2D>().gravityScale = 10;
animator.SetBool("isLedge", false);
isGraping = false;
}
void ClimbingStepOne()
{
GetComponent<Rigidbody2D>().velocity = new Vector3(climbPos.x, climbPos.y + 5, climbPos.z);
}
void Start()
{
portalName = GetComponent<PortalDetector>();
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
audioStep = GetComponent<AudioSource>();
currentY = lastY;
}
// Update is called once per frame
void FixedUpdate()
{
if (isGrounded && !isGraping)
{
if (isWalking)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
if (isCrunching)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * (speed - 1), rb.velocity.y);
}
}
if (isRunning && !isCrunching && !isGraping)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * runSpeed, rb.velocity.y);
}
if (isRunning && isSliding && !isGraping)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * runSpeed, rb.velocity.y);
}
}
void Update()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
currentY = new Vector2(transform.position.x, transform.position.y);
if (Input.GetKey(KeyCode.UpArrow) && isGraping)
{
animator.SetBool("isClimbing", true);
}
if (!isGrounded && isAlsoTrampoline)
{
animator.SetBool("isFalling", true);
}
else
{
isAlsoTrampoline = false;
animator.SetBool("isFalling", false);
}
if (Input.GetKeyUp(KeyCode.CapsLock) && !isCrunching)
{
capsState *= -1;
if (capsState < 0 && moveInput == 0)
{
isWalking = false;
isRunning = true;
jumpForce = 14f;
}
else if(capsState > 0 && moveInput == 0)
{
isWalking = true;
isRunning = false;
jumpForce = 7f;
}
else if (capsState < 0 && moveInput != 0)
{
isWalking = false;
isRunning = true;
animator.SetBool("isRunning", true);
animator.SetBool("isWalking", false);
jumpForce = 14f;
}
else if (capsState > 0 && moveInput != 0)
{
isWalking = true;
isRunning = false;
animator.SetBool("isRunning", false);
animator.SetBool("isWalking", true);
jumpForce = 7f;
}
}
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
}
if (moveInput == 0)
{
animator.SetBool("isWalking", false);
animator.SetBool("isRunning", false);
}
else
{
if (isWalking)
{
animator.SetBool("isWalking", true);
}
if (isRunning)
{
animator.SetBool("isRunning", true);
}
}
if(isGrounded && Input.GetKeyUp(KeyCode.C))
{
cState *= -1;
if (isRunning)
{
if (cState < 0)
{
StartCoroutine (IsSliding());
cState *= -1;
}
else if (cState > 0)
{
StartCoroutine(IsSliding());
cState *= -1;
}
}
else
{
isRunning = false;
isWalking = true;
if (cState < 0)
{
animator.SetBool("isCrunching", true);
isCrunching = true;
}
else if (cState > 0)
{
animator.SetBool("isCrunching", false);
isCrunching = false;
}
}
}
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
animator.SetTrigger("takeOf");
}
if (isGrounded)
{
animator.SetBool("onGround", true);
animator.SetBool("isFalling", false);
amFalling = false;
}
else
{
if ((currentY.y < lastY.y - 2) && amFalling == false)
{
lastY = currentY;
animator.SetBool("isFalling", true);
amFalling = true;
}
animator.SetBool("onGround", false);
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
isJumping = false;
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
}
IEnumerator IsSliding()
{
isSliding = true;
isRunning = true;
isWalking = false;
animator.SetBool("isCrunching", true);
yield return new WaitForSecondsRealtime(.5f);
animator.SetBool("isCrunching", false);
animator.SetBool("isRunning", true);
isSliding = false;
}
}
i just made a debug.log and this is the result
Move Input Val:1 Moving right, eulerAngle:(0.0, 0.0, 0.0)rotation:(0.0, 0.0, 0.0, 1.0)
UnityEngine.Debug:Log(Object)
PlayerController:Update() (at Assets/Scripts/PlayerController.cs:210)
Move Input Val:-1 Moving left, eulerAngle: (0.0, 180.0, 0.0)rotation:(0.0, 1.0, 0.0, 0.0)
UnityEngine.Debug:Log(Object)
PlayerController:Update() (at Assets/Scripts/PlayerController.cs:215)

Trying to generate prefabs over and over in semi-random positions

So I made this code in an effort to start making a script that generates bush objects in my scene randomly, however when in runs it only spawns the first bush. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BushSpawner : MonoBehaviour
{
public GameObject bush;
private float x = 0f;
private float y = -.47f;
private float z = 0f;
private int bushCount = 0;
private Vector3 origPos;
private bool xPlus = false;
private bool xMinus = false;
private bool zPlus = false;
private bool zMinus = false;
// Use this for initialization
void Start()
{
SpawnBushes();
}
// Update is called once per frame
void Update()
{
}
void SpawnBushes()
{
Vector3 startPos = new Vector3(x, y, z);
Instantiate(bush, startPos, Quaternion.identity);
bushCount += 1;
while (bushCount < 100)
{
Vector3 checkPos = new Vector3(x, y, z);
Collider[] intersecting = Physics.OverlapSphere(checkPos, 1f);
if (intersecting.Length == 0)
{
//code to run if nothing is intersecting as the length is 0
Instantiate(bush, checkPos, Quaternion.identity);
bushCount += 1;
}
else
{
//code to run if something is intersecting it
RollPos();
}
}
}
void RollPos()
{
if (xPlus == true
&& xMinus == true
&& zPlus == true
&& zMinus == true)
{
int newRoll = Random.Range(1, 4);
if (newRoll == 1)
{
x += 10f;
}
else if (newRoll == 2)
{
x -= 10f;
}
else if (newRoll == 3)
{
z += 10f;
}
else if (newRoll == 4)
{
z -= 10f;
}
xPlus = false;
xMinus = false;
zPlus = false;
zMinus = false;
}
else
{
int roll = Random.Range(1, 4);
if (roll == 1)
{
if (xPlus == false)
{
x += 2f;
xPlus = true;
}
else
{
RollPos();
}
}
if (roll == 2)
{
if (xMinus == false)
{
x -= 2f;
xMinus = true;
}
else
{
RollPos();
}
}
if (roll == 3)
{
if (zPlus == false)
{
z += 2f;
zPlus = true;
}
else
{
RollPos();
}
}
if (roll == 4)
{
if (zMinus == false)
{
z -= 2f;
zMinus = true;
}
else
{
RollPos();
}
}
}
}
}
I tried putting SpawnBushes in Update to run while a bool is true then make it false when SpawnBushes is done, but that creates the first bush, then 99 other bushes in one random position next to it.
If someone can point me in the right direction or tell me I'm completely off-base I would appreciate it immensely!
Ron Beyer pointed out that I didn't have a large enough range in my Random.Range in RollPos(). Thanks again Ron!

Categories