#💻┃code-beginner

1 messages · Page 354 of 1

radiant frigate
#

hatebin?

#

yes i know

#

no im trying to get it from the MeteorFireScript so it can take the "bullet" rb2d since its a different gameobject

rocky canyon
#

hatebin

radiant frigate
rocky canyon
#

ohh im mixing up people

radiant frigate
#

ohhh

rocky canyon
#

sorry sorry.. lookin at two different scripts 😄

radiant frigate
#

makes sense

#

npnp!

rocky canyon
#

u want the rigidbody from the same object as the MeteorExplosion..
well, right now ur trying to get the rigidbody from the object.. the script is attached to.. not the explosionScript object..
GetComponent is just referencing This gameobject...

for it to reference another object u need to prefix it:
thatOtherObject.GetComponent<Rigidbody2d>();

radiant frigate
#

i know but i want it from the same item as the script is in

rocky canyon
#

so. if the rigidbody is on the MeteorExplosionScript object..
you'd just access it via the variable u assigned just above it..

explosionScript = GetComponent....
explosionScript.GetComponent<Rigidbody2D>();```
tulip plover
rocky canyon
#

use one of those links like the other guy did..

#

send the MeteorFireMovementScript.. b/c thats the script the error belongs to 👍

radiant frigate
#

maybe im just trying something with the rotation that doesnt work or doesnt make sense

#

idk could be

#

my brain operates in weird ways

rocky canyon
# tulip plover what can i do to send my code?

soo, errors 101:

  • the number at the end of the error indicates the line number the error is on
  • if there are (2) numbers, the first number is the character number, and the 2nd is the line number
#
transform.rotation = Quaternion.Euler(0, 0, explosionScript.amountOfBullets * (explosionScript.fireAmount / 360));
``` Something on this line isn't assigned..
tulip plover
rocky canyon
#

soo unity spits out an error when it reaches it

#

explosionScript most likely.. isn't being assigned correctly..

radiant frigate
#

let me check

rocky canyon
radiant frigate
#

thats the problem

rocky canyon
#

👍 good eye

radiant frigate
#

how do i change the instantiate to make them childrens?

tulip plover
tulip plover
rocky canyon
#

you can
use gamething.parent = parentYouWantToSet;

#

orr another way is to use the Instantiate overload that lets u set the parent as one of the parameters

radiant frigate
rocky canyon
#

this one here for example..

#

u could pass in the parent at teh same time u instantiate..

rocky canyon
radiant frigate
#

so i just need to add transform after the transform.rotation?

rocky canyon
#

b/c if theres no hit.. it can't replace the old position u assigned

final glade
#

Hey there,

So basically I have Defence tower game like pvz, where you drag and drop characters in specific check points, I want to change the color of the object once it is in the same checkpoint where another object that contains the script “TissueObject” exists.
Here is my code the issue is I don’t know how think of the logic because i am dealing with three colliders, the collider of the tissue game object itself and the collider of any other tissue game object and the checkpoint

https://paste.ofcode.org/P7nrnbPZCY8vyWCByBsb9a

rocky canyon
#
            if (Physics.Raycast(ray, out RaycastHit hit, distance))
            {
                Debug.Log("Hit something with the raycast.");
                // Spawn the Bullet Hole
            }
            else
            {
                Debug.Log("Didn't hit anything with the raycast.");
                // Don't Spawn the Bullet Hole
            }
``` ❔❓❔
#

if you aren't comfortable with using if else statements.. u probably wanna slow down a bit and try to solidify ur beginner coding concepts

final glade
rocky canyon
radiant frigate
#

yay

tulip plover
rocky canyon
final glade
rocky canyon
#
if(other.CompareTag("Thing1"))
{
// do thing1 action
}```
#

switch statement and a forloop

rocky canyon
#

TryGets aren't expensive

tulip plover
rocky canyon
#

idk bro

ivory bobcat
#

You're already calling GetComponent in Update so you ought not to worry at all about minor details like foreach

blissful yew
#

Any reason why JsonUtility.ToJson(levelCompletionInfo) always writes empty string?

rocky canyon
blissful yew
rocky canyon
#

wherever that raycast is.. ur apprently setting the position of that bullet hole..

#

sooo... whenever you raycast fails don't add a bullethole..

tulip plover
#

i have this error

final glade
#

The problem I am facing is that the collider of the tissue I am dragging has the possibility to collide with one of them basically there are at least 2colliders 1 for the check point and the other is for the tissue if I place the tissue there and then drag another tissue towards it I don’t know which one it would collide with

#

When I tried compare tag it didn’t even work

rocky canyon
rocky canyon
#

not sure of ur set-up or ur game's goals.

wintry quarry
#

As well as reading it yourself

tulip plover
tulip plover
wintry quarry
tulip plover
wintry quarry
#

You can only use variables that have been defined

high marsh
#

okay i still cant figure out how to get my character to go behind the decoration when its y is higher, i followed the tutorial but its just not working

rocky canyon
#

the reason mine works.. is because i have all those variables set up already

ivory bobcat
# blissful yew

Maybe have the backfield serialized? (backfield is private with public access to getter/visible-in-the-inspector)
Json: https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html

Internally, this method uses the Unity serializer; therefore the object you pass in must be supported by the serializer: it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied. The types of fields that you want to be included must be supported by the serializer; unsupported fields will be ignored, as will private fields, static fields, and fields with the NonSerialized attribute applied.
Suggestion: [field: SerializeField]
(Have not tested)

tulip plover
rocky canyon
#

ray is a Ray variable..
hit is a RaycastHit variable..
distance is a Float variable..

#

you have to create them..

tulip plover
#

ok

blissful yew
#

I only read the part about 'class with serializable attribute' and not the next line lmao

high marsh
#

i made it transparency sort by custom axis like the tutorial says but my main character is always on top anyway, they are on the same layer level

rocky canyon
#
float distance = 50f;
Ray ray;
RaycastHit hit;

ray = new Ray(cam.transform.position, cam.transform.forward);

if (Physics.Raycast(ray, out hit, distance))
{
    Debug.Log("Hit something with the raycast.");
}
else
{
    Debug.Log("Didn't hit anything with the raycast.");
}```
heres the full block w/ the context.. (but u still can't just copy and paste)
you need to know how this stuff is arranged in the code, for it to be any kind of benefit to you
cunning narwhal
#

Hi again, back again with a humbling experience with git and git lfs and an overzealous gitattributes file, I think.. and this source control setup is a little.. complex.. and I'm slowly losing any confidence with my attempts at using version control

So I am using git and have the unity gitignore which is good, according to all. Git LFS has option 1 of using the popular gitattributes https://gist.github.com/nemotoo/b8a1c3a0f1225bb9231979f389fd4f3f or option 2, a version of it from someone who sounds like they know better than most on some quirks with it https://github.com/FrankNine/RepoConfig/blob/master/.gitattributes so I chose option 2 out of desperation for something I didnt have to mess with just in case

I got it set up, pushed changes, life was good... very long story short is that I reverted some changes, files stuck around still, I created my Unity project with spaces in the name, git doesnt allow that. Deleted the project, pulled latest from git, so I now have a differnt folder name which may not matter? Anyways loaded it up in unity and it worked but some addons I was using had missing required files which had me reimporting the entre assets and just caused a huge mess. I ended up just scrapping it all and starting over.

What am I doing wrong here?

rocky canyon
#

commiting and pushing are the only things u really need to know how to do

#

if ur not working in a team

cunning narwhal
#

Thanks, I'll just scrap the whole LFS thing and just try to push stuff that isnt media that the default gitignore doesnt catch and save it elsewhere

#

I had a feeling I was overthinking it and I guess I was. This stuff is quite complicated. I'm used to another source control so git is a little odd in how it treats all of the deltas for a file which is how LFS was made to sort of deal with that, but, messy

rocky canyon
#

I've been using it for little over a year now..
I don't know a whole lot about Git but its been easy enough for me to just keep backups on Git

cunning narwhal
#

I'll consider it. Unfortunate that it costs money for something I would only use for this type of stuff

rocky canyon
#

i kept the library locally.. and only pushed the audio I used from then on.. And i still work that way.

rocky canyon
#

basically an alternative of GitDesktop

cunning narwhal
#

It's showing $60 for me with an evaluation period?

rocky canyon
#

but while you learn VC I'd suggest keeping Local Backups on ur HD or GDrive or something, until u feel comfortable..

#

i know thats kinda missing the point of VC.. but its some piece of mind when your working on a project that has weeks, if not months, invested in it

rocky canyon
rocky canyon
#

oh wait.. the evaluation is indefinitely free..

#

they just ask for donation from time to time i guess

cunning narwhal
#

Oh ok, thats not bad then. I'll give it a shot. But yeah anwyays back to my issue though I'll just use the unity gitignore, throw stuff on a repo and make some local backups every now and then and call it a day

#

Thanks for the help

rocky canyon
#

ya, sadly i can't help with LFS stuff.. I had to have a colleague of mine walk me through it last time I used it

#

and even then I really didn't even use it for much.. so I haven't used it since then.. and that was a year or more ago..
so far all of my projects work fine with regular Git..

#

google drive gives you 15 GB.. so thats a good place to store your audio / graphic libraries that would eat up alot of space

tulip plover
final glade
sour ruin
#

Hi, I'm doing some procedural animation stuff and I'd like to be able to test the parameter changes on animations without running the scene. Are there any methods like OnDrawGizmos that get called outside of scene execution where it would be appropriate to do this? (accidentally asked on the advanced channel, deleted that one and reposted here)

flint python
#

Why does it complain about getting null when .Add(test) but for the if statement test is not null. line 19 is just calling the function. Any clue? thanks.

sour ruin
brave compass
sour ruin
sour ruin
brave compass
topaz arrow
#

Universal methods to make your life easier!

Takes in a float value and an image or text and sets the alpha to the specified value

public static void SetImageAlpha(Image image, float alpha)
 {

     if (image != null && image.color.a != alpha)
     {
         float R = image.color.r;
         float G = image.color.g;
         float B = image.color.b;
         float a = alpha;
         image.color = new Color(R, G, B, a);
     }

 }

 public static void SetTextAlpha(TextMeshProUGUI text, float alpha)
 {

     if (text != null && text.color.a != alpha)
     {
         float R = text.color.r;
         float G = text.color.g;
         float B = text.color.b;
         float a = alpha;
         text.color = new Color(R, G, B, a);
     }

 }

Best used in a static class

flint python
#

is there an execution order of awake() for different game object scripts? or can I create an execution order?

summer stump
#

The only way you can define it would be to have your own method that you call from a single object in the specific order you want

#

The need to do so is a bit of a concern though.
What problem are you wanting this solution for?

flint python
# summer stump There is not

i have 2 scripts, 1 assigns a value to a variable, name, in Awake, the other script in Awake gets the name variable. In this case, i can try to move the get part to start then, thanks for the info

summer stump
rocky canyon
# final glade I even tried putting it as you said still does not work! https://paste.ofcode.or...
    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.TryGetComponent(out Green_Script green))
        {
            Debug.Log("Green is nearby!!");
        }

        if (other.TryGetComponent(out Red_Script red))
        {
            Debug.Log("Red is nearby!!");
        }

        if (other.TryGetComponent(out Blue_Script blue))
        {
            Debug.Log("Blue is nearby!!");
        }
    }```
I was mentioning using `TryGetComponent` which is alot better than setting a variable using `GetComponent` and then checking for `null` afterwards..
not sure what about your script isn't working.. But my bet is the setup.. Might try revising it a bit to make it work better for the dragging mechanic..
I just put my code on my mouse cursor b/c I don't have a dragging system to test yet..
#

setup is just Empty Script sitting on the Collider

brisk kindle
#

Hi everyone, I'm trying to get an object to follow my mouse in a room (like first video). I use raycast to determine the object I want to move and move the object following to the position of the mouse on the screen. But when i hit play and drag the object, it doesn't move like in the first video, the object will move like in the second video. Anyone know how to make the object move like the first video? Thanks a lot!

#

My code:

using UnityEngine;

public class Trash : MonoBehaviour
{
    [SerializeField] private Camera mainCamera;

    private GameObject _selectedObject;
    
    private Vector3 _originPos;

    private bool _dragging;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (!_selectedObject)
            {
                var hit = Cast();

                if (hit.collider)
                {
                    if (!hit.collider.CompareTag("trash")) return;

                    _selectedObject = hit.collider.gameObject;
                    _originPos = _selectedObject.transform.position;
                }
            }
        }

        if (_selectedObject)
        {
            var pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y,
                mainCamera.WorldToScreenPoint(transform.position).z);
            var newPos = mainCamera.ScreenToWorldPoint(pos);
            _selectedObject.transform.position = newPos;
        }

        if (Input.GetMouseButtonUp(0))
        {
            if (_selectedObject)
            {
                _selectedObject.transform.position = _originPos;
                _selectedObject = null;
            }
        }
        
    }
    
    private RaycastHit Cast()
    {
        var ray = mainCamera.ScreenPointToRay(Input.mousePosition);

        Physics.Raycast(ray, out RaycastHit hit);
        
        return hit;
    }
}
rocky canyon
#

I kinda see what ur going for now.. but the tissues detecting the collider?
i was thinking it was backwards.. your object was detecting the tissue

rocky canyon
#

all u need is some bounds

#

can manually set them.. or could use a box collider or something...
then clamp the position so it doesn't move any farther

rocky canyon
#

unless the room is an odd shape.. and then i'd have to think a bit more about it

brisk kindle
rocky canyon
#

good luck 🍀

craggy ingot
#

Whenever I am on the ground my velocity continues to rise up until i jump, which is the only time it resets
this is my code:
cs
// using System.Collections;
using System.Collections.Generic;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.Rendering;

public class EX_CharacterMovement : MonoBehaviour
{
public float walkSpeed = 0f;
public float runSpeedMultiplier = 1.5f;
public float jumpForce = 0f;
public float groundCheckDistance = 1.5f;
public float lookSensitivityX = 0f;
public float lookSensitivityY = 0f;
public float minYLookAgnle = -90f;
public float maxYLookAgnle = 90f;
public Transform playerCamera;
public float gravity = -9.81f;
private Vector3 velocity;
private float verticalRotation = 0f;
public CharacterController characterController;

private void Awake()
{
    characterController = GetComponent<CharacterController>();
    Cursor.lockState = CursorLockMode.Locked;
}

private void Update()
{
    float horizontalMovement = Input.GetAxisRaw("Horizontal");
    float verticalMovement = Input.GetAxisRaw("Vertical");

    Vector3 moveDirection = transform.forward * verticalMovement + transform.right * horizontalMovement;
    moveDirection.Normalize();

    float speed = walkSpeed;
    if (Input.GetAxisRaw("Sprint") > 0)
    {
        speed *= runSpeedMultiplier;
    }

    characterController.Move(moveDirection * speed * Time.deltaTime);

    if (Input.GetButtonDown("Jump") && IsGrounded())
    {
        velocity.y = jumpForce;
    }
    else
    {
        velocity.y += gravity * Time.deltaTime;
    }

    characterController.Move(velocity * Time.deltaTime);

    if (playerCamera != null)
    {
        float mouseX = Input.GetAxisRaw("Mouse X") * lookSensitivityX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * lookSensitivityY;

        verticalRotation -= mouseY;
        verticalRotation = Mathf.Clamp(verticalRotation, minYLookAgnle, maxYLookAgnle);

        playerCamera.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
        transform.Rotate(Vector3.up * mouseX);
    }
}

bool IsGrounded ()
{
    RaycastHit hit;
    if (Physics.Raycast(transform.position, Vector3.down, out hit, groundCheckDistance))
    {
        return true;
    }
    return false;
}

}

eternal falconBOT
amber flower
#

I feel dumb whenever I start trying to understand what I'm doing, does anyone have good tips for me to learn?

slender nymph
#

learn the basics using courses like the ones pinned in this channel, then just keep making stuff and learning new concepts as you need them. understanding comes with practice and experience

rocky canyon
#

thats fine to do while ur airbourne.. but when grounded.. it shouldn't be accumulating

#

gravitySim is just a vector that gets added to the input vector i pass into my Move() function

craggy ingot
#

So add on that void to the end of my code?

rocky canyon
#

they're Methods or Functions.. void is the return type (so those functions don't return a variable)
and right here is where u keep adding the gravity... soo in there you could adjust how ur gravity logic is working..

#

no.. u can't just add it on.. u have to adapt it to the script u already have..

#

for 1 you don't call a function called ApplyGravity(); anywhere.. and even if u did the gravitySim variable isn't declared or used for ur characters move() function

craggy ingot
#

oh okay thank you

rocky canyon
#

are you following a tutorial? they should cover how to fix that..

craggy ingot
#

i am however they do not cover it

rocky canyon
#

b/c its a big issue.. esp if u walk off the top of a ledge or something

#

b/c you'll get hurled into the ground if ur velocity keeps growing 😄

craggy ingot
#

yeah dont want that lmao

rocky canyon
#
    private void Move()
    {
        ApplyGravity();
        CalculateSpeed();

        finalVector =
            (groundVector * finalSpeed) +
            (airVector * playerSettings.airSpeed) +
            (Vector3.up * gravitySim);

        if (jump.magnitude > playerSettings.jumpMagn)
        {
            finalVector += jump;
        }

        characterController.Move(finalVector * Time.deltaTime);
        jump = Vector3.Lerp(jump, Vector3.zero, playerSettings.jumpSmoothing * Time.deltaTime);
    }```
for context here is my Movement function
craggy ingot
#

im still a little new to c#, what does the final vector do?

rocky canyon
#

the finalVector i pass into my CCs Move() function is created by adding abunch of different vectors.. and then my gravitySim

#

it does the same thing as ur moveDirection

craggy ingot
#

and then gravity sim is its own declared float/var?

rocky canyon
#

its made up of inputs just like urs

#

this funciton is called in Update.. runs every frame

#

it gets all my vectors.. like urs.. and then adds in the gravity variable.

#

the AddGravity(); is also called every frame..

#

so its constantly either setting the gravity to 1 steady value (when grounded)
or.. adding onto it (if not)

craggy ingot
#

so i make the addgravity void and then declare it in the update void?

rocky canyon
#

like ur jump function's else does..

#

methods

#

u don't call them voids

craggy ingot
#

ah mb

rocky canyon
#

void is its return type..

craggy ingot
#

ohh okay

rocky canyon
#

like ur IsGrounded() method's return type is bool

brisk kindle
rocky canyon
#

it could be a function.. as well public void IsGrounded().

craggy ingot
#

yeah to see if is isgrounded, true or opposite

rocky canyon
#

but hta wouldn't give u back ur true or false..

#

everytime this if/else runs.. that method returns it a bool.

#

so its basically like having a true/false right there in the if condition

craggy ingot
#

is that a bad thing?

rocky canyon
#

but if its void it just does stuff.

#

doesn't give anything back

craggy ingot
#

i thought this was gonna be a lot more simple lol

rocky canyon
#

heres a look at my CC... for context

craggy ingot
#

ok

rocky canyon
#

have you looked over ur script so u know what it does?

craggy ingot
#

what does serializefield do?

rocky canyon
#

and how it works? or is just copy-pasta

rocky canyon
craggy ingot
#

and noo the tutorial was not the best at explaining wheat everything does

#

yeah

rocky canyon
#

public variables can be accessed from outside scripts..

#

which alot of the times u dont want..
so u make a private variable instead.. so it can only be accessed within the script its in

craggy ingot
#

oh okay gotcha

rocky canyon
#

[SerializedField] can take a private variable.. and show it in the inspector..

#

so u can keep a variable private.. but still be able to assign it with the slot.. or see if its there

craggy ingot
#

gotcha

rocky canyon
#

i have alot more visible than i should. for debugging..

#

like i can see my gravitysim

#

as its working

craggy ingot
#

oh and then i see how you did headers for organization i likethat

rocky canyon
#

ya, it gets complicated and i have to keep up with whats what

craggy ingot
#

true

rocky canyon
#

but line 154 is where my apply gravity function is..

craggy ingot
#

i see.. and then where would i define it in my script

rocky canyon
#

and then i just do that modification before i pass in the vector to my cc

#

!code well if u'd post ur code correctly, i'd be able to pinpoint it for you a little better

eternal falconBOT
rocky canyon
#

read the Bot message ^

#

use any of those links is the best thing

#

just paste ur code in, save it, and it'll give u a url to paste back

craggy ingot
#

ok

#

i think i did that right

rocky canyon
#

if u can see it, we can see it

craggy ingot
#

oh ok

rocky canyon
#

i just noticed you have 2 Move() functions

craggy ingot
#

I do?

rocky canyon
#

you do.. you have 1 where u pass in ur movement vectors

#

and then under the jump check u have another

#

interesting.

rocky canyon
# craggy ingot I do?

i'd make it just 1cs Vector3 combinedMovement = moveDirection * speed + velocity; characterController.Move(combinedMovement * Time.deltaTime);

#
  if (IsGrounded())
  {
      if (velocity.y < 0)
      {
          velocity.y = -2f; // Small negative value to keep grounded
      }
      if (Input.GetButtonDown("Jump"))
      {
          velocity.y = jumpForce;
      }
  }
  else
  {
      velocity.y += gravity * Time.deltaTime;
  }``` and then i'd do something like this.. where *if* ur grounded u either set ur gravity to constant `=` or jump and set it to ur jumpforce.. oor your *not* grounded.. and then u can add ur increasing gravity `+=`
craggy ingot
#

well now whenever I hit the ground It lilke slows the fall down right before i hit it

#

like im falling noramlly and it works, but right before I hit the ground my fall slows down

slender nymph
#

whatever you are using to ground check is checking too far

craggy ingot
#

im using a raycast

slender nymph
#

then your raycast is too long

craggy ingot
#

okay let me try shorting it

#

thank you both for your help, it works perfectly now 😄

elder raptor
#

I added a background in my canvas. But I have an issue where the 2D Game Objects are behind the canvas. How do I bring them in front of the background? Or do I have to make the background in world space?

storm pine
# elder raptor I added a background in my canvas. But I have an issue where the 2D Game Objects...

First of all I think your message doesn't belong here, maybe you should ask in #💻┃unity-talk , this is a code channel.
But I have something similar as you can see on the image so I'm going to answer how I did it if you are looking for something similar. What I do is create a Render Texture and associate with the Target Texture of the Camera component. After that on your UI you can create a RawObject that can also be associated with the RenderTexture. Just imagine it like a stream, where the camera is recording on a TargetTexture and you can see that stream on a RawImage like a screen. After that is working you can do some improves like adding the aspect Ratio Fiter on your RawImage to ensure the camera image won't be stretched or compressed and you can preserve the original aspect ratio.
Maybe there is a better way to do that, but I'm kind of new and this is the only way I found.

stoic briar
worthy tundra
#

i forgor the name of the thing where you want to have states instead of strings

slender nymph
#

do you perhaps mean an enum?

worthy tundra
#

yes!!

#

i forgor sorry

honest haven
#
    {
        if (EnemyWeapon.hitTime < PlayerWeapon.hitTime)
        {
            playerWeaponHitFirst = true;
            instance.playerAttackedFirst = true;
            instance.battleActive = true;
        }
        else
        {
            enemyWeaponHitFirst = true;
            instance.enemyAttackedFirst = true;
            instance.battleActive = true;
        }
    }``` This class is on my game manager but when i enter a battle i want to change playerWeaponHitFirst  to false how can i change a static value thats in a function
languid spire
#

show the declaration of playerWeaponHitFirst

#

btw this statement 'a static value thats in a function' makes no sense

burnt vapor
sleek notch
#

Hi can someone help me why it isn't working?

vocal ginkgo
#

How do you make it so that text inputfields don't automatically activate when they're selected with a controller movement input?

wintry quarry
#

If this is for UI you should be using IPointerDownHandler and IPointerEnterHandler

sleek notch
#

Oh

#

Okay

#

Thanks

wintry quarry
#

You don't need to write this code

sleek notch
#

Maybe I'm blind but I haven't seen field for sprite

wintry quarry
#

Change transition mode to sprite swap

sleek notch
#

Damn. Thanks a lot

high marsh
#

how do i make a normal tile?

burnt vapor
high marsh
#

apologies i dont know where im meant to go for this type of question

prisma scroll
#
using BehaviorDesigner.Runtime.Tasks;
using Character.Survivors;
using NPC.Tasks.Survivor;
using Quests.Main;
using UnityEngine;
using UnityEngine.AI;


public class Flee : Action
{
    [SerializeField] private Transform killer;
    public DoQuest doQuest;
    public SharedTransform MainQuestInRange;
    private NavMeshAgent survivor;
    public float safeDistance = Random.Range(31f, 45f);
   

    public override void OnStart()
    {
        survivor = GetComponent<NavMeshAgent>();
        killer = GameObject.FindGameObjectWithTag("Killer").transform;
        if (doQuest._mainQuest != null)
        doQuest._mainQuest.InterruptQuestBot();




    }

    public override TaskStatus OnUpdate()
    {
        if (doQuest._mainQuest != null)
            Debug.Log("Flee" + doQuest._mainQuest.mainQuestStatus.Value + " " + doQuest._mainQuest.gameObject.name);
        if (killer == null)
        {
            return TaskStatus.Failure;
        }

        float distanceToKiller = Vector3.Distance(transform.position, killer.position);
        Vector3 dirToKiller = transform.position - killer.position;
        Vector3 newPos = transform.position + dirToKiller.normalized * safeDistance;

        if (distanceToKiller < safeDistance)
        {
            NavMeshHit hit;
            if (NavMesh.SamplePosition(newPos, out hit, safeDistance, NavMesh.AllAreas))
            {
                survivor.SetDestination(hit.position);
            }
        }
        else
        {

            return TaskStatus.Success;
        }

        return TaskStatus.Running;
    }
}

Hey y'all i have a problem with this code, i want my AI agent to run from the killer, so I made it run to the opposite direction, the problem is, whenever my agent faces the wall or a static object from the environment it stops for a few seconds, what should i do to prevent that from happening?

gray pond
#

hi chat, been following alongside this brackeys video and i'm nearly done with creating my boss, however i've ran into an issue where when i try to set my boss to be able to deal damage to my player but when i've tried to code that in alongside him, it gives me this issue posted below. and you can also see i've added player health but it doesn't want to access it (unless i've missed him adding a reference to my player script)
https://youtu.be/AD4JIXQDw0s?si=sVuzXYmoYgyTdWx6 at 15:38

What's more awesome than an epic boss battle? Let's make one using state machines!

Get 42% OFF Nordlocker: https://nordlocker.net/brackeys
Use code: "BRACKEYS"

● This video is inspired by: https://youtu.be/cXefXSD2SM

● Project Files: https://github.com/Brackeys/Boss-Battle

More videos about 2D:
● 2D Animation in Unity: https://youtu.be/hkays...

▶ Play video
#

also didn't mean to text over this other guy's message, have a look above if you can help him 🙏

deft grail
gray pond
gray pond
north kiln
#

Just ask your question

#

That's not your actual question is it

#

Great well you're not getting any help then

#

!mute 1119185460930039848 15m when you're back you better have changed your pronouns to not be homophobic, and actually ask the real question instead of asking whether people can help with a question you refuse to just ask.

eternal falconBOT
#

dynoSuccess ohmohctp was muted.

autumn tusk
#

ok so im running into an issue with colliders

#

basically im using an a* enemy movement system which means that the system works with two colliders; one 2d box collider thats used as an actual hitbox for player attacks and another 2d circle collider which is used only for navigation and making sure enemies don't get stuck on obstacles while pathfinding

#

this is what an average enemy with this a* pathing algorithm looks like

#

problem im running into is with how my system works for one of the player's abilities

#

basically the player has a "bite attack" that for every collider spawns a pickup, and it spawns 2 per enemy right now, when i only want it spawning one

#

actually might have figured something out

raven ferry
#

Okay i tried my best trying to solve this on my own but were not able to. im currently making my first project which is a 2d hidden objects game. ive been working on mouse nagivation on screen and were able to make both dragging and zooming with mouse wheel to work. but trying to add a camera boundry has prop been the hardest thing in this project.
The game doesnt have a player character but has a custom cursor which ive tried using as a tracking point for the boundry. but i cant seem to fix the issue that when i try to run the game and drag it changes Z from -10 to 0 so i lose view of the game scene. ps. i really had no experince with coding before this project, so this is all very new. i tried incorporating the working CameraMove code that allowed for dragging of the screen with a new code that were supposed to track a player character and lock its camera view, but tried altering it for my need.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMove : MonoBehaviour
{
    [SerializeField]
    GameObject player;

    [SerializeField]
    float timeOffset;

    [SerializeField]
    Vector2 posOffset;


    [SerializeField]
    float leftLimit;
    [SerializeField]
    float rightLimit;
    [SerializeField]
    float bottomLimit;
    [SerializeField]    
    float topLimit;

    private Vector3 Origin;
    private Vector3 Difference;
    private Vector3 ResetCamera;
      private Vector3 velocity;

    private bool drag = false;


    

    private void Start()
    {
        ResetCamera = Camera.main.transform.position;
    }


    private void LateUpdate()
    {


        void OnDrawGizmos()
    {
        //draw a box around our camera boundary
        Gizmos.color = Color.red;
        //top boundry line
        Gizmos.DrawLine(new Vector2(leftLimit, topLimit), new Vector2(rightLimit, topLimit));
        //right boundry line
        Gizmos.DrawLine(new Vector2(rightLimit, topLimit), new Vector2(rightLimit, bottomLimit));
        //bottom boundry line
        Gizmos.DrawLine(new Vector2(rightLimit, bottomLimit), new Vector2(leftLimit, bottomLimit));
        //left boundry line
        Gizmos.DrawLine(new Vector2(leftLimit, bottomLimit), new Vector2(leftLimit, topLimit));
    }

    Vector3 pos = transform.position;
    pos.z = -10;
     transform.position = pos;
        if (Input.GetMouseButton(0))
        {
            Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
            if(drag == false)
            {
                drag = true;
                Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            }

        }
        else
        {
            drag = false;
        }

        if (drag)
        {
            Camera.main.transform.position = Origin - Difference * 0.5f;
            Camera.main.transform.position = Origin - Difference;
            Camera.main.transform.position = new Vector3();
            Mathf.Clamp(transform.position.y, leftLimit, rightLimit);
            Mathf.Clamp(transform.position.y, leftLimit, rightLimit);
        }
        

        if (Input.GetMouseButton(1))
            Camera.main.transform.position = ResetCamera;

    }
}


autumn tusk
#

the rubber duck effect works

north kiln
#

!code

eternal falconBOT
autumn tusk
#

ok so this is my current code which uses colliders instead of gameobjects like i want

    {
    Collider2D[] hitColliders = Physics2D.OverlapCircleAll(transform.position, 5);
        foreach (Collider2D collider in hitColliders)
        {
            if (collider.CompareTag("enemydead")) 
            {
                // collider.transform
                PickupGeneration(collider.transform.position);
                GameObject hitObject = collider.gameObject;

                legitkills++;
                print(legitkills + "killscount");
                
                Destroy(collider.gameObject);
                //animator.SetTrigger("Eating");

            }
        }

    }```
raven ferry
autumn tusk
#

i can use a distanceto function to look for enemies with the "enemydead" tag no problem

#

but is there a foreach function i can apply to all gameobjects in range?

#

an overlapcircle would not work since thats looking for colliders, and every enemy with a* pathing has 2

cosmic dagger
autumn tusk
#

i could stick that in the levelmanager

#

because the issue is some enemies have a* pathing, others dont

cosmic dagger
autumn tusk
cosmic dagger
#

if you place the collider GameObject on an enemy layer, then every collider in that array will be an enemy . . .

#

or what ever layer name you need . . .

autumn tusk
#

what i could do is parent the a* collider, and give it a tag to ignore the player completely

#

then in the foreach function add something to make it ignore all colliders with that tag

cosmic dagger
#

yes, you can use the layer matrix to allow layers to ignore layers . . .

timber tide
#

you can search by interfaces or some component too

#

or your own flag enum

cosmic dagger
timber tide
#

Unity tags suck because they aren't bitwise

autumn tusk
#

i gathered

#

ugh this is kind of a headache

#

ok what if i gave the colliders which need to be ignored a material, and if a collider has that material it gets skipped

#

basically a bootleg tag for that collider

radiant frigate
#

!code

eternal falconBOT
cosmic dagger
autumn tusk
radiant frigate
cosmic dagger
teal mason
#

My NPC will freeze when it starts it's suspicion behavior before moving back to patrolling.

public class AIController : MonoBehaviour
{
    [SerializeField] float suspicionTime = 3f;

    float timeSinceLastSawPlayer = Mathf.Infinity;

    private void Update()
    {
        if (health.IsDead()) { return; }

        if (InAttackRangeOfPlayer() && fighter.CanAttack(player))
        {
            AttackBehavior();
        }
        else if (timeSinceLastSawPlayer < suspicionTime)
        {
            SuspicionBehavior();
        }
        else
        {
            PatrolBehavior();

        }

        UpdateTimers();
    }

    private void PatrolBehavior()
    {
        Vector3 nextPosition = guardPosition;

        if (timeSinceArriveAtWaypoint > waypointDwellTime)
        {
            mover.StartMoveAction(nextPosition, patrolSpeedFraction);
        }
        else
        {
            mover.Cancel();
        }

    }

    private void SuspicionBehavior()
    {
        mover.Cancel();
    }

}
#
public class Mover : MonoBehaviour, IAction
{
    private Direction lastMovementDirection;
    private Vector2 lastDirection;
    public bool isMovingAnimationSet = false;
    [HideInInspector]
    public bool isIdling = true;

    private enum Direction
    {
        Left,Right,Up,Down,None
    }

    private void Update()
    {
        bool isDead = health.IsDead();
        rb.isKinematic = isDead;
        capsuleCollider.enabled = !isDead;
        Debug.Log(isIdling);
    }

    private void FixedUpdate()
    {
        if (rb != null)
        {
            rb.velocity = velocity;
        }
    }

    public void StartMoveAction(Vector2 destination, float speedFraction)
    {
        if (!isMovingAnimationSet)
        {
            isIdling = false;
            isMovingAnimationSet = true;
            ChangeAnimation("Walk", GetLastDirection());
        }

        MoveTo(destination, speedFraction);
    }

    public void MoveTo(Vector2 destination, float speedFraction)
    {
        Vector2 currentPosition = transform.position;
        Vector2 direction = (destination - currentPosition).normalized;
        velocity = direction * maxSpeed * Mathf.Clamp01(speedFraction);

        Direction currentMovementDirection = GetMovementDirection(direction);

        if (currentMovementDirection != lastMovementDirection)
        {
            lastMovementDirection = currentMovementDirection;
            lastDirection = direction;
            Debug.Log("Moving To");
            ChangeAnimation("Walk", direction);
        }
    }

    public void Cancel()
    {
        velocity = Vector2.zero;

        if (!isIdling)
        {
            isIdling = true;
            isMovingAnimationSet = false;
            ChangeAnimation("Idle", GetLastDirection());
        }
    }

    public Vector2 GetLastDirection()
    {
        return lastDirection;
    }

    public bool IsMoving
    {
        get { return velocity != Vector2.zero; }
    }

}
cosmic dagger
radiant frigate
#

does someone know the way to rotate it?

teal mason
#

Motion should stop during suspicion for a few seconds and the NPC should idle in place and then walk back to it's last patrol point. MoveTo() seems to continuously get called when SuspicionBehavior() moves to PatrolBehavior(), which is setting the walk animation repeatedly.

radiant frigate
teal viper
green ether
#

a vector3 is a position not a rotation

teal viper
#

A vector3 is a vector. It's not necesserarily a position

radiant frigate
#

i imagined that, but how could i change the rotation? i searched in the docs and found Euler.angles but that doesnt work either

teal viper
#

But it's not a quaternion for sure

radiant frigate
radiant frigate
raven ferry
#

i edited the code from my previous post a bit so now the drag and reset works again but the boundry box and gizmo lines still dont work

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMove : MonoBehaviour
{
        [SerializeField]
    GameObject player;

    [SerializeField]
    float timeOffset;

    [SerializeField]
    Vector2 posOffset;


    [SerializeField]
    float leftLimit;
    [SerializeField]
    float rightLimit;
    [SerializeField]
    float bottomLimit;
    [SerializeField]    
    float topLimit;

    private Vector3 Origin;
    private Vector3 Difference;
    private Vector3 ResetCamera;
    private Vector3 velocity;

    private bool drag = false;


    

    private void Start()
    {
        ResetCamera = Camera.main.transform.position;
    }


    private void LateUpdate()
    {


        void OnDrawGizmos()
    {
        //draw a box around our camera boundary
        Gizmos.color = Color.red;
        //top boundry line
        Gizmos.DrawLine(new Vector2(leftLimit, topLimit), new Vector2(rightLimit, topLimit));
        //right boundry line
        Gizmos.DrawLine(new Vector2(rightLimit, topLimit), new Vector2(rightLimit, bottomLimit));
        //bottom boundry line
        Gizmos.DrawLine(new Vector2(rightLimit, bottomLimit), new Vector2(leftLimit, bottomLimit));
        //left boundry line
        Gizmos.DrawLine(new Vector2(leftLimit, bottomLimit), new Vector2(leftLimit, topLimit));
    }

    Vector3 pos = transform.position;
    pos.z = -10;
     transform.position = pos;
        if (Input.GetMouseButton(0))
        {
            Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
            if(drag == false)
            {
                drag = true;
                Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            }

        }
        else
        {
            drag = false;
        }

        if (drag)
        {
            Camera.main.transform.position = Origin - Difference * 0.5f;
            Camera.main.transform.position = Origin - Difference;
      //     Camera.main.transform.position = new Vector3();
            Mathf.Clamp(transform.position.y, leftLimit, rightLimit);
            Mathf.Clamp(transform.position.y, leftLimit, rightLimit);
        }
        

        if (Input.GetMouseButton(1))
            Camera.main.transform.position = ResetCamera;

    }
}


teal viper
#

Also, it would only rotate at the scene start(or the object's Start), since it's in Start

radiant frigate
#

what should i debug? the rotation?

radiant frigate
teal viper
radiant frigate
#

thats what it should do

#

let me give you context of the other script

#

each time the loop happens it should go up by 1 fraction of a whole 360º that depends on the amount of bullets

#

so if there are 3 bullets

buoyant knot
#

that doesn’t change the transform as a function of i tho

radiant frigate
#

oh wait i think i messed up and the 360 should go at the start

frosty hound
frigid sequoia
#

Your question is barely understandable and your code doesn't show much since it is relying on a few other scripts we don't know nothing about; but it seems your issue is that you are just adjusting the text to be the variable "score" instead of making it a string with the word first (for example "public string score = "Score: " + score;)

raven ferry
radiant frigate
#

basically it says that z is -1

frosty hound
#

It should be on outside as its own function in your class, not embedded inside another.

radiant frigate
#

and that shouldnt be happening so imma go try to debug more things

buoyant knot
teal viper
radiant frigate
frosty hound
#

OnDrawGizmo will run itself every frame, you don't need to put it inside of an update function.

radiant frigate
buoyant knot
#

actually nvm it isn’t

teal viper
buoyant knot
#

sry i misread

radiant frigate
#

what do you mean by type?

buoyant knot
#

either way, the explosion script should call a method to pass information into the other script

teal viper
buoyant knot
#

amountOfBullets should be a private variable

#

then you will know exactly what you are trying to pass in to the other script

raven ferry
buoyant knot
#

GameObject obj = Instantiate(…);
BulletScript bullet = obj.GetComponent<BulletScript>();
bullet.AssignRotation(amountOfBullets…)(

#

this is how I would do it

radiant frigate
teal viper
buoyant knot
#

with a separate method, you can trace more easily exactly what is getting assigned to debug it

#

and also make sure the timing is right

buoyant knot
radiant frigate
swift crag
#

it can't possibly be any other bullet

#

if Instantiate returned a random object from your scene, it would not be very useful (:

radiant frigate
buoyant knot
#

you use an IEnumerator, that goes through its loop all on yield return null. Those all get instantiated. Then later, Start is called after they are all instantiated, so they all work on the same value of explosionScript.amountOfBullets

swift crag
buoyant knot
#

so the method you are using will never work without passing the information into the bullet script the way I described

teal viper
swift crag
#

it tells you exactly what the property's type is!

radiant frigate
radiant frigate
buoyant knot
#

or rather, it is definitely something that will block it from working

teal viper
# radiant frigate its a quaternion

And that's how quaternions look. They have 4 members and the last one is usually equal to 1.
But then again, everything else being 0 means that it's not rotated.

radiant frigate
buoyant knot
#

each one reads the value in the script after it finished the loop. so they all use the same number

radiant frigate
teal viper
radiant frigate
#

okay

#

on my way

#

brb

buoyant knot
#

as to whether or not the Quaternion math gets you the rotations you want is a different matter that fen and dlich are getting at

#

they are focused on getting the correct rotation given the right input

radiant frigate
#

yeah if im using quaternions it surely isnt working

#

since the math is kinda weird

#

i wanted to use euler angles

buoyant knot
#

in general, you want to multiply quaternions

#

a quaternion represents a rotation operator

radiant frigate
#

rotation operator?

buoyant knot
#

a single quaternion represents taking something with “no rotation” (identity), and rotating it in some way

#

that is what a rotation operator does. it apllies rotation

radiant frigate
#

okay

buoyant knot
#

quaternion multiplication corresponds to composition of rotation operators (which do not commute!)

radiant frigate
#

commute?

swift crag
#

A * B = B * A

#

that is the commutative property

#

and it does not hold for quaternions!

radiant frigate
#

oh

swift crag
#

I forget if they're associative

#

(A * B) * C = A * (B * C)

buoyant knot
#

(quaternion for 90Deg x rotation) * (quaternion for 90 deg y rotation) = (quaternion for both)

radiant frigate
#

okay so basically the order of the factors dont alter the product

swift crag
#

no, they do

buoyant knot
swift crag
#

because the operation is not commutative

#

if it was commutative, then the order wouldn't matter

swift crag
buoyant knot
#

commutative means order does not matter.
quaternion multiplaction is not commutative

radiant frigate
buoyant knot
#

90 deg x then 90 deg y is not the same as 90 deg y then 90 deg x

radiant frigate
#

okay

buoyant knot
#

in general, if you do quaternionA * quaternionB, it’s like you start with rotation of quaternionB, THEN you rotate by quaternionA

radiant frigate
#

cant i just use euler angles?

buoyant knot
#

again: order matters

buoyant knot
swift crag
#

transform.rotation *= Quaternion.AngleAxis(45, Vector3.up)

this always rotates you around the +Y axis

radiant frigate
#

?*

buoyant knot
radiant frigate
buoyant knot
#

that is one reason

swift crag
#

Rotating by the product lhs * rhs is the same as applying the two rotations in sequence: lhs first and then rhs, relative to the reference frame resulting from lhs rotation.

swift crag
buoyant knot
#

all the math of how euler angles work make them not behave well when applying rotation operators using them alone

#

gimbal lock is one symptom of that

radiant frigate
#

but i just want to instantiate an object with a certain z rotation

swift crag
radiant frigate
#

isnt that something basic that should give no problem with euler angles

swift crag
#

Quaternion.AngleAxis(45, Vector3.forward) gives you a 45-degree rotation around the +Z axis

buoyant knot
#

Quaternion.Euler(my desired rotation) * transform.rotation => new rotation

radiant frigate
#

because im getting my mind blown by weird math and i just want to do a 101 thing

buoyant knot
#

is it tho lol

brave compass
#

I remember it as parent * child

swift crag
#

unless you intend to apply that rotation before your original world rotation

buoyant knot
#

oh, maybe all my angles are just backwards

#

and i didn’t notice because 2D

swift crag
#

I had to learn all of this whilst writing code that stored position and rotation offsets from a parent to a child

#

i did it wrong in every possible way lol

buoyant knot
#

i only learned about commutators and shit for rotation operators when I did physical chemistry via quantum mechanics. I didn’t learn any of that shit in normal physics classes

#

which is theoretically when you should learn it

swift crag
#

but first, we need to talk about group theory

#

🎵 🎶

radiant frigate
#

why do i want to rotate a thing in the z axis and im just hearing that you are telling me things that get explained in a quantum mechanics class CatSob

buoyant knot
#

yeah, it makes more sense with group theory

swift crag
#

just like you don't need to understand linear algebra to use transform.TransformPoint

#

Just use the methods provided by Quaternion.

timber tide
#

only thing to know is euler is a poopy head and likes to give you the gimbals

radiant frigate
#

what is even linear algebra lmao

buoyant knot
brave compass
swift crag
#

Quaternion.AngleAxis, Quaternion.LookRotation, Quaternion.FromToRotation, ...

radiant frigate
#

but in 2d it shouldnt matter right?

swift crag
# brave compass I'll give you ten points if you can remember where `Quaternion.Inverse` goes to ...
        for (int index = 0; index < spline.Count; ++index)
        {
            BezierKnot knot = knots[index];
            Transform parent = transforms[index];
            positionOffsets.Add(parent.InverseTransformPoint(splineTransform.TransformPoint(knot.Position)));

            Quaternion knotWorldRotation = splineTransform.rotation * knot.Rotation;
            Quaternion toParentRotation = Quaternion.Inverse(parent.transform.rotation) * knotWorldRotation;
            rotationOffsets.Add(toParentRotation);
        }

i think this is probably right

#

it works, at least

timber tide
#

2d is fine for euler

buoyant knot
#

and your transform.rotation is still a quaternion

swift crag
timber tide
#

2 axis of rotation = not likely to run into gimbals

swift crag
#

assuming you only spin around the +Z axis

brave compass
buoyant knot
#

because unity implements it all as 3D

radiant frigate
#

my brain is getting filled with things it can only dream to comprehend at the moment

buoyant knot
#

in 2D, rotation can be represented solely as one number: z axis angle.
but unity uses the same transform framework for everything. So your transform is a 4x4, and your rotation is a quaternion (instead of just 1 number for an angle)

silent ember
#

is there a working workaround to calling coroutines in a scriptableobject?

timber tide
#

coroutine manager

swift crag
#

do you know what homogeneous coordinates are?

radiant frigate
#

no clue

swift crag
#

yet you are making a 3D video game!

silent ember
buoyant knot
#

also the 4x4 transform matrix includes scale, position, and rotation

swift crag
#

you don't need to know the intricate meaning of a 4x4 transformation matrix

#

you just need to know how to use the tools Unity gives you

buoyant knot
#

yes, you just need to know the rules

swift crag
#

Quaternion.AngleAxis(45, Vector3.forward) produces a 45-degree rotation around the Z axis

timber tide
# silent ember how?

call scriptable object -> scriptable object calls static instance coroutine manager -> coroutine managers makes coroutine on itself

swift crag
#

Who cares how the underlying math works?

radiant frigate
swift crag
radiant frigate
#

ohhh

swift crag
#

you just have a different camera projection matrix

#

I wish Unity just called it a Rotation

buoyant knot
#

first rule of quaternions and 4x4 matrices: don’t crack that shit open to look at or modify the actual contents

swift crag
#

Quaternion (along with the exposed x/y/z/w values) makes it look frightening

radiant frigate
#

what is even W

silent ember
radiant frigate
#

💀

swift crag
#

Check out those static methods.

frail laurel
swift crag
#

Unity offers many ways to create and manipulate rotations.

radiant frigate
buoyant knot
# radiant frigate what is even W

you know how complex numbers live in a complex plane, which is 2D? quaternions are like 4D complex numbers. which is why you should NOT look inside them to try to understand

#

the best way to think of these things is as operators

swift crag
radiant frigate
#

oh so basically i should not try to understand quaternions

swift crag
#

Quaternion.LookRotation isn't being run on a specific object

#

it's just..a method, by itself

frigid sequoia
frail laurel
radiant frigate
buoyant knot
swift crag
frigid sequoia
swift crag
#

you are calling a method on your specific Transform object

radiant frigate
#

now i dont understand what my problem is and how to solve it

swift crag
buoyant knot
#

the only things you need to know about quaternions is:

  1. multiply quaternion => rotate the rotations
  2. they don’t commute
  3. don’t open them. do not read the x/y/z/w
radiant frigate
#

i came here not knowing the answer and now i dont know the question lmao

frigid sequoia
radiant frigate
silent ember
#

@timber tide it gave me a nullreferenceexception on my scriptableobject on the line calling the static instance manager

radiant frigate
#

with this math equation: transform.rotation = Quaternion.Euler(0, 0, explosionScript.amountOfBullets * (360/explosionScript.fireAmount ));

swift crag
#

or the world Z axis?

radiant frigate
#

whats the difference?

timber tide
celest shoal
#

Hello I have here a basic typing effect for a string when it is being displayed with TMP_Text. I want it so that each letter that is type, it will start off with alpha 0 and slowly the alpha will increase to 255/#FF, how would I attempt this? Thank you

swift crag
#

The former will make it spin the same way, no matter which way the bullet is facing

buoyant knot
radiant frigate
#

isnt it the smae?

swift crag
buoyant knot
#

bam. rotation accomplished

frail laurel
silent ember
radiant frigate
silent ember
#

Thanks a lot!

radiant frigate
#

im just getting bombarded with info way above my level i think

swift crag
#

I'm guessing you want the left image.

buoyant knot
# radiant frigate how do i get all that?

Quaternion.Euler(…) gives you a quaternion based on whatever euler angles you give it.
transform.rotation is the quaternion for your thing, which you can use to both read and write.

swift crag
#

Ah, I understand what you are doing now. My 3D example is not helpful.

radiant frigate
#

i want it to rotate on the blue arrow

teal viper
# radiant frigate i now dont even know what i wanted to debug

Code is in most cases Input => Processing => Output. If your output is not what you expect, then you should check the input and that you're aplying the correct processing to it. Now, break down your code with that in mind and tell me what you need to debug.

radiant frigate
#

the rotation

#

but the rotation is completely wrong for what ive heard

teal viper
#

You didn't break down anything. What is your input and what is the processing?

radiant frigate
#

my input are numbers and the processing a math equation?

teal viper
#

Okay, then did you debug your numbers?

radiant frigate
#

nope

#

on my way to do that

teal viper
#

Should've done that like 30 min ago

frigid sequoia
buoyant knot
#

@swift crag i think the quaternion order is a unity implementation detail. For normal quaternions, it is the order I described (A*B = do B then A). But i guess Unity does it in reverse.

#

or the documentation is flipped

swift crag
#

(another reason unity should have just called the damn thing Rotation!)

frail laurel
buoyant knot
#

i just don’t know why the hell they would implement quaternion multiplaction backwards

frigid sequoia
# frail laurel yes

Then why are you surprised when the text that you are specifically telling to replace is getting replaced?

frail laurel
buoyant knot
#

but idk, i do all my quaternion multiplication the correct way, so maybe it’s the unity documentation that is backwards

frail laurel
frigid sequoia
radiant frigate
#

so the problem is even b4 the numbers

swift crag
radiant frigate
#

so its in the for loop inside the coroutine

buoyant knot
frigid sequoia
#

As I said just make it a string and add "Score: " and "High score: " first

buoyant knot
#

it just makes it read chronologically instead of mathematically

frail laurel
plush oxide
#

in the IEnumerator thing, what does yield mean and return mean? the tutorials just mention their existence

swift crag
#

if you string does not start with "Score: ", then you will not see the word "Score"

wintry quarry
buoyant knot
buoyant knot
#

foreach (x in IEnumerator y)
basically does:
while (y.MoveNext)
x = y.Current;

wintry quarry
#

Maybe the text doesn't have room, or maybe other code is overwriting it

#

Or maybe you didn't save your code

plush oxide
buoyant knot
#

so if you do:
Ienumerator MyEnumerator() {
yield return 5;
yield return 3;
Debug.Log(“hi”);
yield break;

then the IEnumerator gives you a 5, then a 3, prints hi, then a break

swift crag
#

If a method returns IEnumerator and has a yield instruction, the compiler turns it into a class with fields that keep track of the data in the method's local variables.

So there's no magic at runtime (:

radiant frigate
buoyant knot
#

yield break makes MoveNext false, which means you’re done

eternal falconBOT
radiant frigate
#

just as loup said b4 it is becuase it take the information once the for loop is completed and therefore they all take the same number

plush oxide
buoyant knot
#

no

#

it returns the number 5

#

then returns the number 3

#

then prints hi (i changed the code)

#

then it breaks (done)

teal viper
plush oxide
#

i see

swift crag
#

when you start a coroutine, you're just throwing your enumerator into a list of enumerators. Unity calls MoveNext on each one each frame by default

buoyant knot
#

unity coroutines use IEnumerators, and interpret the things you yield return to know how/when to wait

radiant frigate
swift crag
#

So MeteorFireMovementScript has a Start method.

teal viper
buoyant knot
#

so if your IEnumerator does yield return new WaitForSeconds(5);
and it is a coroutine, then unity will do that, get WaitForSeconds object, it looks in that object and decides to wait for 5 seconds before going on in that IEnumerator

swift crag
#

In that method, you check explosionScript.amountOfBullets.

radiant frigate
buoyant knot
#

you can use Ienumerators that are not coroutines

swift crag
#

Start runs the frame after you create something.

#

By this point, amountOfBullets is 6. Everyone sees 6 and does the same thing.

teal viper
buoyant knot
#

but if you start coroutine and give an ienumerator, unity will try to interpret the outputs to try to figure out waiting times or timing etc

swift crag
buoyant knot
#

you can also just make an Ienumerator to give a bunch of numbers, or strings, or whatever

#

@plush oxide make sense?

radiant frigate
#

my problem is im really bad at words, and i tend to forget the name even if i understand it

plush oxide
#

ill take like 2 mins and read

buoyant knot
#

ienumerators are used outside of coroutines, and you should know both. IEnumerators are really fucking useful

teal viper
plush oxide
#

im just trying to understand what you meant by It returns 5 then 3

plush oxide
#

what does returning 5 and 3 actually do

radiant frigate
#

what is considered the basics?

swift crag
#
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs "5"
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs "3"
#

You can yield return whatever you want in a method that returns IEnumerator.

#

IEnumerator<T> requires you to yield return a specific type. It is the generic equivalent to IEnumerator.

raven ferry
#

im trying to create a object that will always be in the center of the screen that i can track, so like not at (0.0) but at the center of the screen no matter where i move inside a scene, what would that be called? having a hard time finding it by searching up on google/youtube. im having trouble with the boundries in my game tracking the cursor, so i thought maybe having a center object thats connected to the screen that the camera can lock onto thats then moved by the cursor drag might be worth trying

raven ferry
#

thank you so much, i will look that up

plush oxide
swift crag
#

i can't help you if you just say "i don't get it"

plush oxide
#

sets its Current property to 5

#

idk what enumerator current means

teal viper
swift crag
#

Current is the ... current value

plush oxide
#

do you have an example perhaps

swift crag
#

It is part of the IEnumerator interface. Every IEnumerator can tell you the current value

plush oxide
#

okay

#

i guess ill read for 5 mins

burnt vapor
# plush oxide idk what enumerator current means

When you implement an IEnumerable and ask for the inner enumerator, Current is one of the properties that exist inside of it. It determines the current value to return, which in the case of a Coroutine would be WaitForSeconds for example, assuming you yielded with this class.

swift crag
#
List<int> integers = new() { 1, 2, 3 };
var enumerator = integers.GetEnumerator();
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs 1
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs 2
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs 3
burnt vapor
#

The other important part is MoveNext, which moves to the next value or returns false if there are none left.

teal viper
plush oxide
#

ill just stop asking questions and wasting your time, because each time someone answers it has another word or something I dont know, so Ill just get to this later i guess

swift crag
#

"I don't get it" x100 is not useful

plush oxide
#

see

#

if I told you what I dont get

plush oxide
#

we would be here for a while

radiant frigate
#

i will check into that

swift crag
#

bet

plush oxide
#

fair enough

#

in the SIMPLEST terms possible, in real life terms perhaps, what is an enumerator

#

how bout we start there

#

so I can build on it

swift crag
#

let me make a thread

plush oxide
#

oka

mystic heart
#

I'm trying to make this little app (preferably in unity) where I have two phones, one phone is closed and the other has basic UI with just one button. Whenever I press that button, a notification should appear on the other phone, but i have zero clue 😆

#

Would I require a server of any kind that uses cloud code to push it?

#

I'm currently looking at the mobile notification package from Unity, it has like 80% of what I need

raven ferry
#

ive been trying to trouble shoot this for a bit but no luck. im trying to fix a issue with my game where the game finally respects the boundries i set in so the camera doesnt go past it, but now it keeps jittering between (x,y) and (-x, -y). Any suggestions for the cause?

timber tide
#

best to post code so people can help with the issue besides trying to guess

raven ferry
#

here is the script that causes jittering

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMove : MonoBehaviour
{
    [SerializeField]
    GameObject Cursor;

    [SerializeField]
    float timeOffset;

    [SerializeField]
    Vector2 posOffset;


    [SerializeField]
    float leftLimit;
    [SerializeField]
    float rightLimit;
    [SerializeField]
    float bottomLimit;
    [SerializeField]    
    float topLimit;

    private Vector3 Origin;
    private Vector3 Difference;
    private Vector3 ResetCamera;
    private Vector3 velocity;

    private bool drag = false;

     void OnDrawGizmos()
    {
        //draw a box around our camera boundary
        Gizmos.color = Color.red;
        //top boundry line
        Gizmos.DrawLine(new Vector2(leftLimit, topLimit), new Vector2(rightLimit, topLimit));
        //right boundry line
        Gizmos.DrawLine(new Vector2(rightLimit, topLimit), new Vector2(rightLimit, bottomLimit));
        //bottom boundry line
        Gizmos.DrawLine(new Vector2(rightLimit, bottomLimit), new Vector2(leftLimit, bottomLimit));
        //left boundry line
        Gizmos.DrawLine(new Vector2(leftLimit, bottomLimit), new Vector2(leftLimit, topLimit));
    }

    private void Start()
    {
        ResetCamera = Camera.main.transform.position;
    }

    void Update()
    {
      //cameras current position
      Vector3 startPos = transform.position;

      //Players current position
      Vector3 endPos = Cursor.transform.position;

      endPos.x += posOffset.x;
      endPos.y += posOffset.y;
      endPos.z = -10;

      //smoothly move the camera towards the players position
      transform.position = Vector3.Lerp(startPos, endPos, timeOffset * Time.deltaTime);
      transform.position = endPos;
      
      transform.position = new Vector3

      (
        Mathf.Clamp(transform.position.y, leftLimit, rightLimit),
        Mathf.Clamp(transform.position.y, leftLimit, rightLimit),
        transform.position.z

      );

    }
    private void LateUpdate()
    {

        Vector3 pos = transform.position;
        pos.z = -10;
        transform.position = pos;
        if (Input.GetMouseButton(0))
        {
            Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
            if(drag == false)
            {
                drag = true;
                Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            }

        }
        else
        {
            drag = false;
        }

        if (drag)
        {
            Camera.main.transform.position = Origin - Difference * 0.5f;
            Camera.main.transform.position = Origin - Difference;
            Camera.main.transform.position = new Vector3();
       //     Mathf.Clamp(transform.position.x, leftLimit, rightLimit);
          //  Mathf.Clamp(transform.position.y, bottomLimit, topLimit);
        }
        

        if (Input.GetMouseButton(1))
            Camera.main.transform.position = ResetCamera;

    }
}


frosty hound
timber tide
#

also bounds class if not using cinemachine

raven ferry
frosty hound
#

I'm confused why you need lateupdate here at all, if you're moving your camera in Update and already clamping it to the left/right limit? Also your clamping of the transform is using the y value for both x and y.

raven ferry
# frosty hound I'm confused why you need lateupdate here at all, if you're moving your camera i...

ive been following guides and tried to understand how the code works, im still not too sure on the difference between late update and update but this is how atlest 1 portion of the code in this script was set up. this is like my first experince with real coding and game making so im trying to learn as much as i can lol.
so if i understand correctly i should remove late update and put its contents under update? oh shit yeah thanks i completly overlooked that! thanks!!

icy junco
#

just a quick question when adding aiming is it best to use an animation for aiming or just like moving the object with code?

queen adder
frosty hound
icy junco
queen adder
#

np

queen adder
hushed hinge
#

and right now it have tutorial boards

#

i also made a parkour part where you have to run over the holes since you can't jump over them because of the platforms above

frail laurel
#

anyone could help?

rich adder
#

thats what happens when you use AI to write

#

it doesn't work and you cannot fix it

stoic glen
#

Where can I find those settings? I can't find it inside Player settings

rich adder
#

not a code question. did you try the search bar in the Player Settings?

stoic glen
rich adder
stoic glen
#

On Mobile

rich adder
#

also are you trying to test on mobile how ?

polar acorn
#

Why would it? You don't have anything anywhere that adds 5 seconds to the timer. Maybe show where you're trying to do that and we can try to see why it doesn't

keen needle
#

Is there a way to change the name of element 0, element 1....?

rich adder
zenith cypress
#

^ or a custom editor/property drawer

wintry quarry
keen needle
#

is not working

swift crag
#

on the elements

#

oh, I see

#

I misread the name of the list

swift crag
wintry quarry
keen needle
wintry quarry
#

then that's why

#

it will take on whatever name you give

#

also pretty sure it should be called name not Name but not sure if that makes a difference

silent ember
#

Hello. I know that this should cause unity to crash because it's an infinite loop but it doesn't.

#

Instead, it continues counting and the game runs normal.

#

I'm confused on why this is the case.

cosmic quail
wintry quarry
#

whereas a loop without that would not allow the rest of the game engine to run between iterations

silent ember
#

ohh

#

So what if I want to freeze the game while the conditions aren't met?

#

Let's say until SkillQueueNumber is more than or equal to 10 perhaps

languid spire
#

remove the yield

#

and add a yield break at the end

wintry quarry
silent ember
#

like this?

wintry quarry
#

0 is not more than 10

#

so the loop will simply be skipped

silent ember
#

oh silly me

wintry quarry
#

also there's no reason for this to be a coroutine now

#

since it isn't doing any yielding

silent ember
#

This is just a simple example I'd like to be explained

wintry quarry
# silent ember like this?

well in this code you make a variable, set it to zero.
Then the while loop checks if 0 > 10, and it's not, so it skips the loop
Then the function ends

#

this all happens immediately

silent ember
#

because before I thought that if you put "true" on the while condition, it would be an infinite loop and crash the game

wintry quarry
#

Yes if you do that without a yield inside, that will happen

languid spire
#

but, as Praetor says, without a yield actually breaking processing there is no need for it to be a Coroutine

west sonnet
#

I have an object that I want to animate just once. What's the easiest way to do that?

silent ember
#

This was the original code and I was wondering why it prematurely stops without fulfilling any of the conditions

wintry quarry
wintry quarry
silent ember
#

But anyways, thank you all for the help

sage spruce
#

@west sonnet uncheck the looping and it will play only once

wintry quarry
#

If you want to, you can always attach the debugger and step through the code

#

and see what's going on

silent ember
west sonnet
wintry quarry
silent ember
#

but yeah, yield shouldnt be there

languid spire
west sonnet
#

For some reason in Unity, you can't just do Animation.Play()?

wintry quarry
wintry quarry
#

(the legacy one)

sage spruce
#

@west sonnet set it not to loop and then enable animator component from script

zenith cypress
#

Can also use it with the animator to force play an animation state in your animator controller

wintry quarry
silent ember
silent ember
wintry quarry
#

but yeah this code is scuffed

#

for one, it seems to think arrays are 1-indexed instead of 0-indexed?

#

for two, there's no handling for the case when there are no skills available in any slot

#

In that case, the loop will go on infinitely

languid spire
silent ember
#

I didnt think of that

#

I guess it should check whether at least one of the slots has a skill?

#

is that right?

meager sentinel
#

Which way can i make a bullet which i can change the speed even after it's been spawned?

wintry quarry
#

a for loop would do just fine

#

and be less risky

west sonnet
#

I can only using animation.play() if I change the animation to legacy?

meager sentinel
wintry quarry
#

you can do it with either

#

but you will need to provide the parameter with either one

wintry quarry
wintry quarry
empty ice
#

Hi guys, quick question.
Im trying to make a very simple main menu with Ui button, when the button is clicked music fades out and scene is switched. However the scene does switch after some time but for some reason the music doesnt fade out. Why could that be?

public AudioSource MenuMusic;

public void StartShift() 
{
    StartCoroutine(PlayGamee());
}


public IEnumerator PlayGamee() 
{
    MenuMusic.volume = 90;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 80;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 70;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 60;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 50;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 40;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 30;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 20;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 10;
    yield return new WaitForSeconds(0.5f);
    MenuMusic.volume = 0;
    SceneManager.LoadSceneAsync(1);
}
silent ember
empty ice
#

Oh. That explains it, I feel like an idiot now. I've been trying to fix this for like an hour now and nothing helped.

languid spire
#

Also, make it a loop please

meager sentinel
wintry quarry
silent ember
#

and I think that using a while loop would be the easiest

empty ice
#

So to my understand im supposed to do
1 then 0.9f and so on?

wintry quarry
rocky canyon
#

rigidbody.velocity =

rocky canyon
#

would directly set the rigidbodies velocity

wintry quarry
silent ember
empty ice
rocky canyon
#

while volume > 0

wintry quarry
rocky canyon
#

then when its not.. loop ends

wintry quarry
#

you literally just write a basic for loop that goes over the array once

empty ice
silent ember
wintry quarry
meager sentinel
wintry quarry
#

Of course you can

#

you can do whatever you'd like

meager sentinel
wintry quarry
meager sentinel
summer stump
wintry quarry
summer stump
#

Wait, are you writing rb.velocity.x =
?

meager sentinel
wintry quarry
#

For the record, there is literally nothing you can do with AddForce that can't be done by setting velocity and vice versa. They are two differently shaped handles that ultimately do the same thing

#

The only end-result of calling AddForce is that the velocity of the body changes

silent ember
wintry quarry
#

You are overcomplicating it

#

write a single for loop that iterates over the array and finds the first available skill it sees.

meager sentinel
#

My Visual Studio seems to be bugged or something now

#

yesterday it worked just fine with unity but now it doesn't detects errors

summer stump
silent ember
wintry quarry
meager sentinel
#

because in AddForce you can do transform.forward

#

but you cant in velocity

wintry quarry
languid spire
wintry quarry
wintry quarry
#

you are making stuff up!

meager sentinel
wintry quarry
#

show your code

#

and your error

#

transform.forward exists so long as the code you're writing is in a MonoBehaviour derived class

#

if not, that has nothing to do with AddForce and velocity, it's a whole separate issue.

meager sentinel
meager sentinel
wintry quarry
wintry quarry
#

it's an error because your code is nonsense

languid spire
wintry quarry
#

rb.velocity = transform.forward

#

remember it's new Vector3(x, y, z) not new Vector3(anEntireVector3, y, z)

meager sentinel
wintry quarry
#

You copied it incorrectly

#

show where the unity docs have that

meager sentinel
silent ember
#

Thanks!

polar acorn
wintry quarry
wintry quarry
# meager sentinel

I think what you're missing here is that velocity accepts ANY Vector3. Doesn't matter where it comes from. So you have many options there. You can:

  • Create a new one with new Vector3
  • Use one from another place or something such as transform.forward

But new Vector3(transform.forward, 0, 0) itself just does not make any sense, because transform.forward is not a number you can plug into x in the x, y, z of a Vector3, it's a whole vector itself.

meager sentinel
#

Well i dint know that

swift crag
#

instead of parking your car in the garage, you're trying to park the car in itself

wintry quarry
#

Let's say you have a garage with 3 spaces for cars. Instead of putting 3 cars in your garage, you're trying to put another whole 3 car garage in one of the 3 spaces 😭

west sonnet
#

Am I doing something wrong here? My animation isn't playing

polar acorn
wintry quarry
west sonnet
polar acorn
swift crag
#

The example code does suggest you can do that...

#

although it also provides an explicit layer ID

wintry quarry
swift crag
west sonnet
west sonnet
#

Hence why I also put Base Layer

swift crag
#

i would start by making sure that:

  • the animator is doing anything at all
  • your code is even running
polar acorn
swift crag
#

I have seen that syntax before, where you specify both the layer name and the state name

#

I don't use the Animator much so I don't know too much there

west sonnet
#

My code is running. Everything else in the same method works just fine. I don't see any activity in the animator tho, not sure why

#

Do I need to create a seperate empty state so that I can transition from the empty state into the animation?

swift crag
#

You would want that, yes

west sonnet
#

What am I doing wrong now? If I press B, nothing happens

#

The trigger isn't enabled in the animator

wintry quarry
west sonnet
#

Yeah, I've confirmed with Debug.Log

wintry quarry
#

Where did you put the log

west sonnet
#

Just below the anim.SetTrigger, so the Debug.Log happened when I pressed B

wintry quarry
#

Then either:

  • You will see an error in the console about the trigger not existing (or some other error)
  • the trigger is being set
west sonnet
#

But I'm not getting either of those, nothing is happeniing

wintry quarry
#

The bottom one is happening if you aren't getting an error

#

show screenshots of things

#

maybe:

  • Your state machine is not set up to do anything with the trigger
  • Your state machine is reverting to another state quickly
  • You have error logs disabled in your console
  • You're looking at the wrong animator
#

These are all possiblities

west sonnet
#

PizzaGained trigger is enabled in screenshot because I manually enabled it with mouse click

#

but it's not normally enabled

wintry quarry
#

Are you selecting the animator that's actually in the scene?

brazen mortar
#

shufflee is a List<T>. Am I correct in thinking that this code will set shufflee to be a shallow copy of what it previously referred to? Or is there a better way to do it?

slender nymph
#

you are correct. it's a new List object containing the same elements

brazen mortar
#

thanks

shadow briar
#

Does anyone have any links to any references i can use for not using Update() / fixed update() for movement and the sort.
So using WASD to move around, and each input calling its selected movement method, so W for Forward as an example.

Cause far as i know from Unreal constantly using Update is somewhat a no no, but not sure if Unity is different in that regard.
I've been searching around for any videos, scripting manuals that could help me and so far just been a brick wall, as each thing i've found just makes use of Update.

slender nymph
#

there's nothing wrong with using Update when you need to, and for the most part you will need to use Update for movement, just maybe not polling each key individually. if you use the input manager look into using the GetAxis methods. if you use the input system you can use events to react to changes in input which will clean up your Update and FixedUpdate methods significantly

rich adder
shadow briar
#

Alright, cheers for the information, many thanks.
I'll give this input system a look and take it in forward that its not wrong to use Update.

Cheers again

pallid sandal
#

rigidbody.AddForce(Vector3.up * 500);
doesnt work to make player jump

#

i tried everything (with code and rigidbody in inspector)

slender nymph
#

you're likely overwriting velocity somewhere

pallid sandal
#

maybe that

slender nymph
#

probably

pallid sandal
tiny dagger
#

does anyone know how to turn this off?

#

the low resolution aspect ratios

languid spire
#

might not be a bad idea to not subtract and add to the timer in the same method

rotund forum
#

Hello.

I am having a terrible time of trying to make my play rotation function work in a way that looks good. The attached video, in the later half, shows a jitter when I am holding a directional input, moving the player, and rotating the camera at the same time.

The following is the function, HandleRotation(), that I call in fixed update. My inputs are assigned in update. The player's rigidbody is not kinematic and has interpolation on.

If anyone can help me I would greatly appreciate it. The function does work I suppose. But it looks quite ugly when I'm rotating the camera while moving the character.

{
    Vector3 _targetDirection = Vector3.zero;

    _targetDirection = _cameraTransform.forward * _playerInputManager._verticalInput;
    _targetDirection = _targetDirection + _cameraTransform.right * _playerInputManager._horizontalInput;
    _targetDirection.Normalize();
    _targetDirection.y = 0;

    if (_targetDirection == Vector3.zero)
        _targetDirection = transform.forward;

    Quaternion _targetRotation = Quaternion.LookRotation(_targetDirection);
    Quaternion _playerRotation = Quaternion.Slerp(transform.rotation, _targetRotation, _rotationSpeed * Time.deltaTime);

    transform.rotation = _playerRotation;

}```
languid spire
rocky canyon
#
private void UpdateTimer()
{
    timer -= decrementSpeed * Time.deltaTime; // decrement timer each time the method is called

    if (timer > 0) // if the timer is still greater than 0
    {
        // log the time and set the color
        timerText.text = $"Time: {timer:F1} seconds"; // string interpolation to add time variable inside string
        timerText.color = timer <= 10 ? Color.red : Color.white; // ternary operator to set color w/o bulky if/else
    }
    else
    {
        // timer is 0 or less
        Debug.Log("Time's up!");
        Respawn();
        timerText.enabled = false;
    }
}```
here's how i would do it 🆓 🐝 
i just wanted to refactor some code to get my brain working today 😄
knotty ferry
#

dam

rotund forum
languid spire
rotund forum
eternal needle
buoyant knot
#

rigidbody does so via physics engine. transform does not.

#

so if you change transform, then rigidbody API will fight you over it

languid spire
#

also doing Slerp(current, final, t) rather than Slerp(start,final, %)

buoyant knot
#

in general, if you have a rigidbody, you should try to only move your object via the rigidbody commands

#

if you do not, then the transform is the only thing to mess with

eternal needle
buoyant knot
#

if your rigidbody is kinematic mode, then I would try MoveRotation.

#

if it is dynamic, then you’re basically applying a bunch of torque/forces to try to rotate it, and it will be more difficult to get a specific rotation

knotty ferry
#

anyone know any script ideas how to make when obstacle respawns it would add 20 seconds to the timer?

rich adder
#

its pretty tame stuff

eternal needle
rich adder
#

start small, build up

buoyant knot
#

make a system to control timer. make a system to respawn obstacle. then make them communicate

knotty ferry
willow scroll
buoyant knot
#

addvalue is a custom function you wrote

#

we’re not going to know wtf it does

eternal needle
rich adder
#

"add value 20 to the text"
you probably want to add it to a variable and display that instead

rocky canyon
#

timer still counting down..
and the else statement will run once more after getting below 0

honest haven
#
public class UniqueID : MonoBehaviour
{
    [SerializeField]
    private string uniqueID;

    public string ID => uniqueID;

    private void Awake()
    {
        if (string.IsNullOrEmpty(uniqueID))
        {
            uniqueID = System.Guid.NewGuid().ToString();
        }
    }

    private void OnValidate()
    {
        if (string.IsNullOrEmpty(uniqueID))
        {
            uniqueID = System.Guid.NewGuid().ToString();
        }
    }

    private void Reset()
    {
        uniqueID = System.Guid.NewGuid().ToString();
    }
}``` Hi how can i get this to work on prefabs duplicates please
eternal needle
knotty ferry
rich adder
#

well which method/condition do you have to update UI ?

knotty ferry
rich adder
knotty ferry
knotty ferry
rich adder
knotty ferry
#

i can add debug

#

to check

rich adder