#💻┃code-beginner

1 messages · Page 689 of 1

wintry quarry
#

like misspelling Update

gusty folio
#

game object i s active and so is the component

#

and update is correct

wintry quarry
#

prove it

#

show some screenshots and your code

gusty folio
#

just refreshed unity

#

gimme a sec

#

its the playermanager script

wintry quarry
#
  1. Show your code
  2. Make sure the script is not being disabled when you enter play mode
gusty folio
gusty folio
wintry quarry
#

!code

eternal falconBOT
wintry quarry
#

Check your console for errors too

gusty folio
#

scripts running now

#

i think i can fix it

#

probably

#

k fixed it

#

two references to the same compmonent that resulted in null reference

#

and stopped the rest of the code from running

rich ice
#

not a code question but yeah that is weird. i've never noticed that before

sweet bough
#

I dont know why, but the rotation of player doesnt really work

using UnityEngine;

public class TeleportTrigger : MonoBehaviour
{
    public Transform targetLocation;
    public string playerTag = "Player";
    public GameObject ObjectToActivate;
    public Transform playerObject;
    public bool invertRotation;

    private void OnTriggerEnter(Collider player)
    {
        if (player.CompareTag(playerTag))
        {
            float cameraX = playerObject.localEulerAngles.x;
            player.transform.position = targetLocation.position;

            float targetY = targetLocation.eulerAngles.y;
            if (invertRotation)
                targetY = (targetY + 180f) % 360f;

            player.transform.rotation = Quaternion.Euler(0, targetY, 0);
            playerObject.localRotation = Quaternion.Euler(cameraX, 0, 0);

            if (ObjectToActivate != null)
                ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
        }
    }
}
#

it is 5 am so i maybe shitcoded

gusty swallow
#

my camera started jittering after i added the sprint mechanic

rich adder
#

👇

eternal falconBOT
gusty swallow
#
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;

    public float speed = 12f;
    public float originalSpeed = 12f;
    public float sprintSpeed;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    void Start()
    {
        sprintSpeed = speed * 1.2f;
    }
    void Update()
    {
        //Code below checks is the player isGrounded
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
        //Gravity
        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }
        

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        
        Vector3 move = transform.right * x + transform.forward * z;

        //Sprinting mechanic 
        if (Input.GetKey(KeyCode.LeftShift))
        {
            speed = sprintSpeed;
        }
        else
        {
            speed = originalSpeed;
        }
        
        //Moves the character with the character controller
        controller.Move(move * speed * Time.deltaTime);

        if (Input.GetButton("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
        
    }
}
rough sluice
#

Can we use ChatGPT instead of reading the entire documentation while working on a 3d/2d game?

frosty hound
#

Who's going to stop you?

rough sluice
#

Why? What happened?

rich ice
#

nothing, they mean there's nothing stopping you from doing that. if it works for you then go for it, just make sure to double check with the docs if something goes wrong

rough sluice
#

Ok

kindred path
#

Can someone help please, why is transform not working

wintry quarry
kindred path
#

what?

wintry quarry
#

If you don't know what that means you probably should try to follow the basic tutorials pinned in this channel

#

To learn how to write a script in Unity

rough sluice
#

Try doing this:public class PlayerCam : MonoBehaviour

kindred path
wintry quarry
#

Same advice

kindred path
#

Thank you though

wintry quarry
sweet bough
acoustic belfry
#

hey, if i want to make a enemy spawn a couple of proyectiles in a row with delay, i should use a timer or a coroutine?

eternal needle
acoustic belfry
#

holup, i been investigating and

what are ivokes, and why people dont use them instead of coroutines?

eternal needle
#

theres no real need to use it

tiny laurel
#

Would it be better to handle things like bullet penetration/ricochet and tumbling on the server and replicate it off to clients? Or should I simulate this on the client and hope the server also simulates something identical?

acoustic belfry
eternal needle
acoustic belfry
eternal needle
acoustic belfry
#

makes sense

eternal needle
#

especially if you have a lot of logic already happening in update, and this extra functionality needs to happen based on a condition, it can get messy

hot wadi
#

I tried to git push the Library folder in my project but it is said to be machine-specific and recommended to be ignored. Is it true?

keen dew
#

yes

eternal needle
#

there is more than just the library you want to exclude

hot wadi
#

Wow, there are really too many to include

burnt vapor
#

Can also just get the gitignore from the general repo

#

This one is guaranteed to be up to date

covert obsidian
#

im p sure unity is interpretting 99,999,999 in a float as 1e+08, which is just 100 million. is there a way to stop this?

naive pawn
covert obsidian
#

imma switch the > 999... to >= 1b in my code and it shouldn't be an issue anymore

thanks

spare tiger
#

guys can anyone tell me about this?? like am following code moneky tutorial and this is the error which is coming

wintry quarry
pulsar tapir
spare tiger
#

thxx guys! i smh found the fix !!

worldly iris
#

Hey guys. Im working on some kind of 3D Endless Runner (inspired by Race the Sun). I've build a system where i move the whole world around the player and not the player himself (exept for the y Axis, things like jumping and stuff). Now I switched from a Rigidbody to a Character Controller since I don't want to use unity physics anyway and the slope movement thingy is very useful for the things I'm trying to achieve.
The only thing that bug's me is that i cant lock the x and z position like I would with an rb. Sometimes when my player touches some Obstacles he gets pushed around. I tried working around that by always moving him back to 0,0,0 but tbh, I'm not very proud of this solution.
Does anyone have an idea of how I could lock my player or knows of a way to 'fake' something like that?
Any help is appreciated, thanks in advance :>

tardy needle
#

is there a way to make floats only have discrete values, for example it only changes in steps of 3 so if its value is 5.2 it snaps to 6

naive pawn
#

no, you can make that calculation yourself though

slender nymph
#

you can use unity's Snapping.Snap method to do it manually

naive pawn
#

damn i keep forgetting that's a thing

tardy needle
#

i see, thanks

slender nymph
#

you'll also want to make sure you're only using that where you plan to display the value, using it every time you change the value will mean you won't properly accumulate small changes

royal citrus
#

How do I use Graphics.DrawMeshInstancedIndirect? Currently, I'm drawing a lot of meshes by

  • calculating matrices with a compute shader
  • sending the data from the GPU
  • using the matrices on the CPU to call Graphics.DrawMeshInstanced
wintry quarry
# royal citrus How do I use Graphics.DrawMeshInstancedIndirect? Currently, I'm drawing a lot of...

This is a great little article about it https://share.google/OITG8vEP8SsFXfShI

#

God I'm going to throw my phone in a river for doing this share.google nonsense 😡

grand snow
#

there we go lets fix that

royal citrus
dusty kite
#

Hi guys! I'm new to unity and I've been looking for a roblox-like camera style tutorial online but couldn't find anything or the camera didn't work for me (tried using cinemachine and scripting), and wanted to ask if anyone knows a tutorial for that kind of camera or knows how to do it themselfes 🙏

naive pawn
#

could you describe what kind of behaviour you want

dusty kite
dusty kite
rich ice
#

i think there's an example asset for that on the asset store

dusty kite
#

👀

rich ice
dusty kite
#

I'll check it out ty!

woven crater
#

hmmm i know that get component is heavy but can i use it in ray casting context? like having hovering effect by getting the script component when cast mouse on it. i know IPointerEnter but i already used it for something else and there seem like no way to make it work on specific layer

sour fulcrum
#

getcomponent is fine and usually necessary, its just usually very avoidable via caching and easy for beginners to spam in heavy loops like update

#

just give usage of it some thought and if you think its the right call it probably is

woven crater
#

yeah i heard it heavy but not sure how heavy its so i worry of using it abit

sour fulcrum
#

yeah people overexaggerate to drill it into beginners

woven crater
#

hah yeah i had the feeling. thank

eternal needle
wise cairn
#

hi so i'm trying to figure out cinemachine, i got it installed but i cant really figure out what i'm meant to do

frosty hound
#

Why did you install it then? What are you planning on using it for?

wise cairn
#

honestly idk

#

i just heard it's very helpful so i'm trying to get it set up

frosty hound
#

Well, if you can't communicate your need, then naturally you won't know what you're meant to do because you'd have nothing to actually look up.

#

"very helpful" is very vague.

blissful creek
#

Newbie question here, need help with the logic for a practice scenario, in a function that updates every frame (60fps), essentially to choreograph a 1-2 punch.
So I have something like:

public void OnUpdate(float deltaTime)
{
  _countFrame++;
  if (_countFrame % 60 != 0) return;
  punchOne();

  if (_countFrame % 120 != 0) return;
  punchTwo();
}

If I’m not mistaken, punchOne occurs every second, whilst punchTwo every two seconds. How can I prevent the punchOne from occurring when punchTwo happens? I can imagine a boolean but wonder if there’s a more efficient way.

keen dew
#

If you prevent punchOne from happening when punchTwo happens, it will alter between punch one and punch two with one second pause between them. Is that what it's supposed to do?

blissful creek
#

Yeah

cedar wing
#

How can i tell my bean to always spawn to the left of the car door no matter where the car is rotated?

keen dew
# blissful creek Yeah
if (_countFrame % 120 == 0) {
    punchTwo();
}
else if (_countFrame % 60 == 0) {
    punchOne();
}
blissful creek
#

Ah, simple and neat. Thanks

eternal needle
eternal needle
cedar wing
#

oh yeah empty gameobject sounds goated thank you!

blissful creek
eternal needle
#

Well actually it'd be slightly different given you wouldn't want to check if it's equal to 1 second

eternal needle
manic umbra
#

Hey all, i need some help with transitioning to C# in unity..
for 4-5 years ive always been playing with lua in various game engines, meaning i can get a pretty nice workflow running in my head when im coding. Since lua is nothing similar to C#, i dont know where to start learning/transitioning to it. If anyone has some tips, steps, tutorials, anything helps. Thanks!

eternal needle
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

nimble apex
manic umbra
#

Is it the layout? or should i learn basic keywords or whatever it is

eternal needle
#

You follow a structured course and focus on what they're teaching you. Or if youre pretty good at coding in other languages, just spend some time making console apps or random features to get used to the language. Google along the way

manic umbra
#

Ill try find a decent course to get

#

Thanks for the help

nimble apex
#

if u interested in 2D games, in my college normally we will start with two projects

#

angry birds or flappy birds

#

dont ask why its all birds

blissful creek
eternal needle
blissful creek
#

Hmm I don’t understand how it can limit it to just one time each

eternal needle
sweet bough
#

I dont know why, but the invertion of player rotation doesnt work (it teleports the player without inverting his rotation)

using UnityEngine;

public class TeleportTrigger : MonoBehaviour
{
    public Transform targetLocation;
    public string playerTag = "Player";
    public GameObject ObjectToActivate;
    public Transform playerObject;
    public bool invertRotation;

    private void OnTriggerEnter(Collider player)
    {
        if (player.CompareTag(playerTag))
        {
            float cameraX = playerObject.localEulerAngles.x;
            player.transform.position = targetLocation.position;

            float targetY = targetLocation.eulerAngles.y;
            if (invertRotation)
                targetY = (targetY + 180f) % 360f;

            player.transform.rotation = Quaternion.Euler(0, targetY, 0);
            playerObject.localRotation = Quaternion.Euler(cameraX, 0, 0);

            if (ObjectToActivate != null)
                ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
        }
    }
}
blissful creek
#

(@eternal needle) Yeah that made sense as it would stay at timer >= 1 thus keeping them alternating.

In the other scenario where I just want them to occur once, I imagine it would be

if (timer == 2 && numPunches % 2 == 0) {
  punchTwo();
} else if (timer == 1 && numPunches % 1 == 0) {
punchOne();
}
#

Wait that was redundant if I just needed the timer

eternal needle
blissful creek
#

Ah

west sonnet
#

Is recoil for guns typically done with animation or through code? Because I'm thinking for consecutive shots, the recoil force should start from where the gun is, which could be mid recoil, not from it's starting position

rocky canyon
#

both

#

i prefer coded animations on weapons

#

tweens or lerp

eternal needle
# sweet bough I dont know why, but the invertion of player rotation doesnt work (it teleports ...

add logs or step through with the debugger and see what these values are. if a value doesnt align with what you think it should be, you at least have more insight as to whats not working.
also you shouldnt really be reading the eulerAngles then using that to set the rotation. the rotation is stored as a quaternion, and many different euler angles can represent one quaternion. The value might not be what you expect

hallow sun
hallow sun
#

then yeah, that line undoes the rotation from the previous line if player.transform and playerObject are the same object

sweet bough
# hallow sun then yeah, that line undoes the rotation from the previous line if player.transf...
using UnityEngine;

public class TeleportTrigger : MonoBehaviour
{
    public Transform targetLocation;
    public string playerTag = "Player";
    public GameObject ObjectToActivate;
    public bool invertRotation;

    private void OnTriggerEnter(Collider other)
    {
        if (!other.CompareTag(playerTag)) return;

        other.transform.position = targetLocation.position;

        Quaternion targetRot = targetLocation.rotation;
        if (invertRotation)
            targetRot = Quaternion.AngleAxis(180f, Vector3.up) * targetRot;

        other.transform.rotation = targetRot;

        if (ObjectToActivate != null)
            ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
    }
}
#

i tried this but it isnt working

hallow sun
#

what do you want to happen? this one is very different from the last one you sent

sweet bough
#

thanks for help

hallow sun
#

aight as long as it works

old vector
#

I'm trying to get the angular data from the Meta Quest 2 controller, but it's not very reliable. Has anyone worked on this before?

azure iris
#

im trying to make a projectile bounce off a wall but everytime it hits said wall it goes in the wrong direction

if (linecastHit.transform.CompareTag("BounceBox") & bulletCurrentStats.currentBounce > 0)
{
  Vector2 reflect = Vector2.Reflect(bulletrb.transform.position, linecastHit.normal);
  bulletrb.transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(reflect.y, reflect.x) * Mathf.Rad2Deg);
  bulletrb.linearVelocity = new Vector2(Mathf.Cos(transform.rotation.eulerAngles.z * Mathf.Deg2Rad), Mathf.Sin(transform.rotation.eulerAngles.z * Mathf.Deg2Rad)) * bulletCurrentStats.currentSpeed;
  print("Hit" + linecastHit.transform.name + ", " + reflect + Mathf.Atan2(reflect.y, reflect.x) * Mathf.Rad2Deg);
  bulletCurrentStats.currentBounce -= 1;
}
#

how would i fix that

naive pawn
#

i think you're supposed to reflect the velocity, not the position?

azure iris
#

that was all it was 💀

#

its working now, thank you

naive pawn
proper cloud
#

anyone know why the camera is not following the player?

grand snow
#

probably needs a position control to make it follow as well as look

proper cloud
#

Cinemachine should do everything, but it doesnt work :/

grand snow
#

It does work and quite well when you use it properly

proper cloud
#

true

#

thus my problem

grand snow
#

They have some doc pages for common use cases ^

frail hawk
proper cloud
echo copper
#

guys, help, plz

#

what does that mean

naive pawn
echo copper
#

ow ok

naive pawn
#

it's pretty much just what the error said

echo copper
#

yes, i thought the model variable is not a variable with name "model", but something different

#

sorry

gleaming haven
#

what is generally the best way to make the light for a flashlight? if I put the light at the flashlight itself (which is in the bottom right corner of the camera), then the light doesn't illuminate the middle of the screen, which looks weird. if i put the light in the center of the camera itself, it looks weird too because the light isn't coming from the flashlight. is there a best practice for this?

ivory bobcat
frigid sequoia
#

I am wondering if doing a string comparison at start of a relatively spameable method is not ideal, would you call this an issue?

grand snow
frigid sequoia
grand snow
#

then the mapping for colour should still use the enum value

#

you can .ToString() when you actually need that

frigid sequoia
#

The enum to text is not exactly 1 to 1 conversion to the actual text I want to display

#

The class that instantiates this already has a switch to do the conversion to pass it as a string, should I change it to have it on this other class?

ivory bobcat
frigid sequoia
#

Like what would be the preferred way to do this

grand snow
#

should then have a mapping that uses the enum as a key and THAT contains the display text and colour

ivory bobcat
#

So relative to design, don't use string comparison. Use the enum to compare.

brave robin
#

Alternatively, if you need more functionality or info than what an enum can do, use a scriptable object class instead

ivory bobcat
#

Almost anything but strings. Flexibility equates to undefined behavior and ambiguity.

frigid sequoia
#

Yeah, I just changed the place of enum conversion, I was just placing somewhere else since I was already using the namespace for it there lol

bright zodiac
#

and c++

grand snow
#

Yea c# will intern duplicate strings

bright zodiac
#

I'd go with String.Create and spans here and get 0 alloc

ivory bobcat
grand snow
#

overkill much

#

im sure some niche situations require such measures but probably not right now 😆

frigid sequoia
#

I just find it way easier to read this way

grand snow
#

personal preference, both produce a new string

#

Its nice when doing something like $"{numA}/{numB}"

#

the object automatically does ToString()

bright zodiac
#

with that in mind, it only matters once unity moves to coreClr

royal citrus
#

Does anyone know how to use Graphics.DrawMeshInstancedIndirect with shader graphs?

royal citrus
jaunty axle
#

Why does the jump animation behave like that? Also, the fall animation is supposed to play when I fall, but it's not happening

wintry quarry
#

And use the sample texture 2D node

#

It's a little awkward

queen adder
#

Hey so I was working on a shooting enemy I want it to follow the player from a distance how do I go about it please

digital topaz
#

Seems annoying to have to commit all 3rd party assets to git, when you should just be able to check them out quickly with your project packages. :/
But now i'm trying to use github actions to build my project and it doesn't have things 😦

rich adder
queen adder
#

Its a top down 2d game with basically infinite procedural generation so I don’t think it’s advisable or possible

rich adder
#

still vague.. plenty of games made with procedual generated

queen adder
#

Path finder can’t be used for an infinite world

#

You can’t generate a surface

rich adder
#

so you generate it at runtime

modest dust
queen adder
#

Either way it’ll still be jittery because my current method is basically the same thing

#

I’m using a physics2d overlap circle to check

rich adder
#

check what?

queen adder
#

The enemy checks for the player with it then when it detects the player it moves to it at stops at X distance from the player but now each time the player moves again the enemy try’s to keep up chasing jittery movement

modest dust
#

Then move the enemy only if the player moves a certain distance away from the enemy, not immediately when the distance is larger than X.

queen adder
#

I’ll try that and see

modest dust
#

Or add a delay, or smooth out the movement over time.

vague sequoia
#
    {
        Vector2 WasdDelta = inputManager.WasdDelta;

        Vector3 forward = new Vector3(Orientation.forward.x, 0, Orientation.forward.z).normalized;
        Vector3 right = new Vector3(Orientation.right.x, 0, Orientation.right.z).normalized;
        Vector3 moveDir = (forward * WasdDelta.y + right * WasdDelta.x).normalized;

        float currentSpeed = walkSpeed;


        if (WhatIsGround)
        {

            if (WasdDelta.magnitude < 0.1f && moveDir == Vector3.zero)
            {
                StateMovement = MovementState.Idle;
            }
            else
            {
                StateMovement = MovementState.Walking;
            }

            if (inputManager.IsKeyDown(InputManager.InputAction.Run))
            {
                currentSpeed = runSpeed;

                StateMovement = MovementState.Running;
            }

           


            Rb.linearVelocity = moveDir * currentSpeed;
             


        }    ```What could be causing the character to not stop instantly?,From what I see, it takes a while to go to idle and not because it is not instantaneous.
teal viper
vague sequoia
teal viper
vague sequoia
#

Sorry, the last thing I did didn't work, and in the idle part when Wasd delta doesn't receive one, its magnitude will be 0 and if that happens we force it to stop

#

but what happens is that instead of going from Running to idle when no input is received, this happens: first it is Running, then Walking and finally idle and it takes a few seconds before being idle (a second but it is noticeable) so it takes a while to stop

solemn grotto
#

hey guys i just wanna ask what would be a simple way to make a drag system where i can just hold left click on a cube and drag it around

vague sequoia
rich adder
solemn grotto
rich adder
#

do you have an example?

solemn grotto
verbal dome
# vague sequoia

GetAxis has some smoothing by default, try GetAxisRaw instead or adjust the smoothing for those axes in the input manager

rich adder
royal citrus
#

Is there a way to prevent Graphics.DrawProcedural and other similar functions from executing on a specific camera? I have a camera that simply renders black because of split screen.

sharp bloom
#
private IEnumerator WaveFunctionCollapse()
{   
    while (cellsToBeProcessed.Count > 0)
    {
        yield return new WaitForSeconds(0.01f);

        
        SortCellListByDomainCount();
        currentCell = cellsToBeProcessed[0];

        currentCell.CollapseSelf();
        currentCell.changed = true;

       
        if (currentCell.currentState == CellStateName.red)
        {
            foreach (var n in currentCell.neighbours.Values)
            {
                n.RemovePossibility(CellStateName.red);
            }
        }

        cellsToBeProcessed.Remove(currentCell);
        UpdateAllCells();
    }
}

Been working on this random map generation based on the wave function collapse method, this is sort of a dumb version of that algorithm right now. I can right now create patterns such as the image, but I only have one rule, red can't be next to red.

But for example, I would want rules such as "blue must be next to at least one other blue" . But I can't really wrap my head around it, does anyone have good examples on how this is done?

soft knoll
#

Hay

#

Anyone

rich ice
# soft knoll Hay

unless you have a question, most messages like "hi" or "hey" will go ignored

undone depot
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Interactor : MonoBehaviour
{
    public float interactDistance;
    public PlayerInput playerBinds;
    private InputAction interact;
    public Camera cam;

    [SerializeField]
    private LayerMask interactableMask;

    private void OnEnable()
    {
        interact = playerBinds.Player.Interact;
        interact.Enable();
    }

    private void OnDisable()
    {
        interact.Disable();
    }

    private void Update()
    {
        if (
            Physics.Raycast(
                cam.transform.position,
                cam.transform.forward,
                out RaycastHit hit,
                interactDistance,
                interactableMask
            ) && playerBinds.Player.Interact.IsPressed()
        )
        {
            Debug.Log("Interact Successful");
        }
    }
}```

Does anyone have a clue on to why the if statement in Update() would cause an Object is not set to an instance of an object error?
keen dew
#

Either cam , playerBinds, playerBinds.Player or playerBinds.Player.Interact is null

twin pivot
#

My solution was to make an array with 10x + y being the number the gameobject is stored in

#

For example if a blue tile is at (2,7) it would be myGameObject[27]

#

Although if you're using a 10 by 10 grid you're probably gonna have to find a different solution

next fable
#

hey guys, very beginner question but I'm not sure why my override method aren't being called - the base versions are instead?

#

oh, sorry if I'm interrupting haha

twin pivot
#

Heres 2 ways i think you could do it

  1. You put the different colored tiles in seperate arrays and check every single one
  2. You add colliders in a + shape and shoot a ray at it and check if it collides with anything (maybe add an interface to each type of tile and check for that?)
next fable
#

the base function is ``` public virtual void MoveTowardsWaypoint()
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Vector3.SqrMagnitude(targetPos - transform.position) > 0.05f)
{
RotateTowardsWaypoint(Quaternion.LookRotation(targetPos - transform.position, Vector3.up));
}

    for (int i = vehicles.Count - 1; i >= 0; i--)
    {
        vehicles[i].CheckLocalPosition();
        vehicles[i].vehicle.CheckCollision();
    }
}```
#
    {
        for (int i = vehicles.Count - 1; i >= 0; i--)
        {
            vehicles[i].vehicle.MoveAndRotateTowardsWaypoint();
        }
    }
#

the override function's like this - but in-game, the stuff in the base function's being called instead

sour fulcrum
#

is the unit the type of class that override function is on?

nimble apex
#

this is a code design question

currently i have a join request system, backend is operational and there are no problem on sending/reciving data

however, the system is driven by two UI , one big one small

  1. big one can only be opened when player click on the small one, no other ways
  2. either of them can only exist one, no duplications
  3. there can be unlimited requests as long as the room is not filled
  4. each requests should have separated timer , terminated after 10 seconds received

my question is, with this kind of design , u must store it somewhere else when u received it right? and u need to think of what to store

next fable
nimble apex
#

u think i should use ..... a model class + unscaled time?

next fable
#

they move differently, I have a vehicle state machine with a reference to a vehicle unit it's attached to

#

referenced like this

nimble apex
#

Dictionary <class,float>

where model class is the response , float is the unscaled time

opaque isle
#

Hello, i am a programming beginner and I would like someone to review my save/load game script

#

Just to give me advice, if its bad/good.

#

Where could I post my code snippet?

median hatch
#

no idea what Loc_Inv... is

#

make it more readable

#

apart from that seems okay

opaque isle
#

Oh yes I understand, yes i put weird variable names

sharp bloom
#

I got something working, not perfect since it generates dead-ends but we're getting there

opaque isle
#

@median hatch And one more, this is the read function. That reads the saved file

median hatch
#

whatever FAB is

keen dew
#

You don't need to check if Count > 0 inside the for loops. The loops don't do anything if the count is 0

median hatch
#

personally i create classes and store data there, then simply serialize that class

#

then onLoad i grab the json file and store that into the same class

#
void OnSaveSystem(int index)
    {
        playerData.dateTime = DateTime.Now.ToString();

        string playerJson = JsonUtility.ToJson(playerData, true);
        File.WriteAllText(Application.dataPath + $"/StreamingAssets/Save{index}/PlayerData.json", playerJson);

        string weaponsJson = JsonUtility.ToJson(weaponData, true);
        File.WriteAllText(Application.dataPath + $"/StreamingAssets/Save{index}/WeaponsData.json", weaponsJson);

        string droneJson = JsonUtility.ToJson(droneData, true);
        File.WriteAllText(Application.dataPath + $"/StreamingAssets/Save{index}/DroneData.json", droneJson);
    }

dont know how standard it is but works well for me

keen dew
#

Also you can convert the keys and values directly to lists, no need to do that manually

opaque isle
#

@keen dew Is that a function or?

#

Becuase I use a dictionary for inventory, and dictionary cant be serialized to json

keen dew
#

Post the !code as text, I'm not going to retype it from the screenshot

eternal falconBOT
opaque isle
#
public static void SaveGameData(bool BASE_SAVE)
{
        bool dirExists = System.IO.Directory.Exists(path);
        if (!dirExists)
        {
            System.IO.Directory.CreateDirectory(path);
        }
        GameData gameData = new GameData();
        GameManager gameManager = GameManager.ReturnSelf();

        for (int i = 0; i < gameManager.GlobalInventoryDictionary.Count; i++)
        {
            if (gameManager.GlobalInventoryDictionary.Count > 0)
            {
                gameData.Glob_Inv_Scr.Add(gameManager.GlobalInventoryDictionary.ElementAt(i).Key);
                gameData.Glob_Inv_Int.Add(gameManager.GlobalInventoryDictionary.ElementAt(i).Value);
            }
        }
        for (int i = 0; i < gameManager.LocalInventoryDictionary.Count; i++)
        {
            if (GameManager.ReturnLocalInventory().Count > 0)
            {
                gameData.Loc_Inv_Scr.Add(gameManager.LocalInventoryDictionary.ElementAt(i).Key);
                gameData.Loc_Inv_Int.Add(gameManager.LocalInventoryDictionary.ElementAt(i).Value);
            }
        }
        if (gameManager.knownRecipes.Count > 0)
        {
            gameData.knownRecipes = gameManager.knownRecipes;
        }
    if(BASE_SAVE)
    {
        foreach(var FAB in SystemManager.GetSystemManager().fabricatorArray)
        {
            FabricatorData NEW_DATA = new FabricatorData();
            NEW_DATA.isFabricatorOperational = FAB.isFabricatorOperational;
            NEW_DATA.isWorking = FAB.isWorking;
            NEW_DATA.storedAmountOfItems = FAB.storedAmountOfItemsToFabricate;
            NEW_DATA.FAB_ID = FAB.fabricatorID;
            gameData.FAB_DATA.Add(NEW_DATA);
        }
    }

    string json = JsonUtility.ToJson(gameData);
    System.IO.File.WriteAllText(path + "/gameData.json", json);
    
}
rugged beacon
#

most object pool video i seen on youtube implement their own pooling, why is that? is unity's object pooling implementation bad

keen dew
#
gameData.Glob_Inv_Scr = new List<?>(gameManager.GlobalInventoryDictionary.Keys);
gameData.Glob_Inv_Int = new List<?>(gameManager.GlobalInventoryDictionary.Values);

And the same with Loc_Inv_*, Replace ? with the correct types

slender nymph
rugged beacon
slender nymph
#

no. but my point was that the reason you see so many object pool videos that implement their own is because the feature simply did not exist in most versions of the editor

rugged beacon
#

ok thanks i will stick to unity's

median hatch
keen dew
#

I'm not sure what you mean. It creates as many entries as there are values

#

The end result is the same as in the original code

thick sedge
#

a bit out of context but where do the games on steam keep their saving files?

polar acorn
#

Wherever they want to

thick sedge
polar acorn
#

Look up [Game] PC Save location on google and do that

#

They can go literally anywhere. AppData, Documents, User folder, Registry, ProgramData, all sorts of places

polar acorn
#

Next time, just google it. You'll find the answer in seconds

willow iron
#

i have several nested if statements. if ANY of these if statements are false, i need to do something. is there a way to do this that is neater than just including else statements after every single if?

wintry quarry
#

Show the code if you want more specific advice

frosty hound
#

Don't nest them, and use a bool flag to determine the results.

bool checkPassed = true;

if (condition 1)
   // Do this
else
    checkPassed = false;


if (condition 2)
   // Do that
else
    checkPassed = false;

// ---

if (!checkPassed)
  // Something failed

gusty swallow
#

why does the sprint mechanic make my camera jump sometimes

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;

    public float speed = 12f;
    public float originalSpeed = 12f;
    public float sprintSpeed;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    void Start()
    {
        sprintSpeed = speed * 1.2f;
    }
    void Update()
    {
        //Code below checks is the player isGrounded
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
        //Gravity
        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }
        

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        
        Vector3 move = transform.right * x + transform.forward * z;

        //Sprinting mechanic 
        if (Input.GetKey(KeyCode.LeftShift))
        {
            speed = sprintSpeed;
        }
        else
        {
            speed = originalSpeed;
        }
        
        //Moves the character with the character controller
        controller.Move(move * speed * Time.deltaTime);

        if (Input.GetButton("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
        
    }
}
wintry quarry
#

(one other issue - you should not be calling Move twice per frame. Sum the vectors and call it once)

gusty swallow
cloud obsidian
#

hi guys

#

i have a problem

#

i just downloaded unity

#

and guider on youtube opened script with smth like that

#

but when i doing all the same

#

it opens notepad

#

can someone help me with that

gusty swallow
polar acorn
#

Also don't crosspost you end up getting the same answer in multiple places and wasting more of people's time

wintry quarry
eternal falconBOT
cloud obsidian
chrome apex
#

Guys, I'm going through absolute hell trying to create and IK system for my fingers for grabbing terrain. It's all kinds of uneven and I've tried different methods but they all have cases where they don't work perfectly

#

would a finger ragdoll system be a stupid idea in this case?

#

but I guess I would need gravity to be applied in self space of the hand (due to rotations)

south nexus
#

hey im really struggling to on how to make top down melee combat are there any tutorials on this?

polar acorn
#

That's a vague question, break the problem down into smaller problems and find out which thing you don't know how to do

frail crane
#

any guesses on why my score isn't updating? I assigned the tmp in the editor

{
    private Rigidbody2D rb;
    public float moveSpeed;
    Vector3 lastVelocity;
    private int score = 0;
    public TMP_Text scoreText;


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {

        rb = GetComponent<Rigidbody2D>();
        float randomNumX = Random.Range(-1.0f, 1.0f);
        float randomNumY = Random.Range(-1.0f, 1.0f);
        rb.linearVelocity = new Vector2(randomNumX * moveSpeed, randomNumY);


    }

    // Update is called once per frame
    void Update()
    {
        lastVelocity = rb.linearVelocity;
        scoreText.text = score.ToString(); 
    }
    void OnTriggerEnter2D(Collider2D collision)
    {
        Scene scene = SceneManager.GetActiveScene();
        SceneManager.LoadScene(scene.name);
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        var speed = lastVelocity.magnitude;
        var direction = Vector3.Reflect(lastVelocity.normalized, other.contacts[0].normal);
        rb.linearVelocity = direction * Mathf.Max(speed, 0f);
        moveSpeed = moveSpeed + 5;
        if (other.gameObject.tag == "paddle")
        {
            score++;
        }
    }
}

naive pawn
#

(also wouldn't you want to have lastVelocity updated in FixedUpdate?)

#

anyways i digress

#

have you tried debugging stuff? does the score actually change? is the tag check passing?

frail crane
naive pawn
#

either the collision message isn't being called or the condition isn't passing

willow iron
#

is there any way to make a variable visible to other scripts while not visible in the inspector for unity?

naive pawn
#

or [NonSerialized]

#

or make it a property

willow iron
#

👍

naive pawn
#

or make it internal instead of public

#

probably shouldn't do that one, but eh just throwing it out

#

you should figure out if you want the variable to not be in the inspector, or not be serialized as a whole

atomic holly
#

Hello
I want to create a type that will store all colliders2D of a gameobject and its childrens. So I wanted to create a struct serializable like this :

[Serializable]
public struct PlanAttributes
{
    public GameObject Plan;
    public List<Collider2D> PlanColliders;
}

But, I don't know if it is better to use a class instead of a struct. I want in awake to store in the list all colliders of the plan. What is the best approach to do that ?

rich adder
#

but really you can use both, is just that some people say and microsoft documentation, you typically would have structs only contain immutable data

atomic holly
eternal needle
rich adder
frail hawk
#

i don´t think you would be so conserned, to care about wheter you would use heap or stack

#

unless you are planning to have hundreds or thousand of these structs

rich adder
#

but yeah you should not be too worried and stick to class when in doubt lol this is #💻┃code-beginner anyway

willow iron
#
    {

        if (quickstart)
        {
            yield return new WaitForSeconds(3);
            returnToWander();
        }
        else
        {
            returnToWander();
        }
    }```

so i want to stop the above coroutine, but my ide states that i need to call `StopCoroutine(lostPlayer());` with an argument. does it matter what i put as the argument? i mean im stopping the coroutine so it doesn't matter
rich adder
#
Coroutine myCo;
...
myCo = StartCoroutine(Whatever());
..
StopCoroutine(myCo);```
atomic sierra
#

Im trying to recreate flappy

#

but I want the sprite to jump the same amount if I click space again, so how do I stop this slight pause from happening?

#

I feel like its trying to negate the downward force

slender nymph
#

reset its vertical velocity to 0 before applying force when you jump

atomic sierra
#

so like rb2d.velocity = 0

#

or smthn

#

like this basically?

frail hawk
#

why don´t you just try it out

atomic sierra
#

now the sprite just slowly drifts down to the platform

frail hawk
#

read again what boxfriend said

atomic sierra
#

oh

#

oh now I get it.

atomic sierra
frail hawk
#

glad you could fix it

ebon peak
#

how to fix this

#

not this

frail hawk
#

you got errors in your code, why not post some code so we can say more

polar acorn
low copper
#

I'm a beginner and want to to explore creating a login system. Can someone give me the name of location to store authentication data within unity? I'm happy to do my own research but I just don't know the terms to look up.

rich adder
low copper
#

I am referring to authenticating with a server. I'm coming from the web dev world...we have session. I don't know what unity uses.

rich adder
#

depends how you authenticate, typically you would store a token and if done properly a refresh system for such a token

low copper
#

that is exactly what I would like to do

rich adder
low copper
#

I have the login scene/web requests all set

#

Ok great. I will research player prefs. Thank you so much for the link too. I will read it right away.

#

Can I just get a quick pointer on how to handle refreshing?

#

I assume that is not part of the PlayerPrefs system

frail hawk
#

not the savest way to save sensitive data like that

rich adder
#

refresh is done like every other system does it on the web

#

check if token exist, check the expiration date and if you auto refresh and expired, then use a refresh token

#

i would not recommend making your own when premade solid solutions already exist

ebon peak
#

how to fix this guys

low copper
#

@rich adder : Thanks

ebon peak
#

errore

rich adder
# ebon peak eroor

you've been answered multiple times what to do and you promptly ignored it and now are asking the same thing in crossposting multiple channels..

ebon peak
#

no one answered me

rich adder
ebon peak
#

look it the time he answered me

#

and when i post it

#

and i closed dc thats why

rich adder
#

what about it ? you still ignored it and posted the same thing again

ebon peak
#

what post

rich adder
#

also what does this have to do with being in the probuilder channel

ebon peak
#

idk lol

#

im new is there a channel for these errores

polar acorn
ebon peak
#

ok i closed dc

rich adder
ebon peak
#

how

polar acorn
ebon peak
#

look im new new like i dont know any thing

rich adder
#

how do you stay alive ?

polar acorn
ebon peak
#

sorry but i did not understand what did u say

polar acorn
#

Clear the console. See what errors stay.

#

then post those errors

ebon peak
#

ty for answer

rich adder
ebon peak
#

ty

#

i just stared yesterday

rich adder
#

thats fine but you are jumping too far ahead if you don't even know the basics of the editor, start with the structured courses on learn

ebon peak
#

my bad if i igored u or somthing

#

okie

#

can u help me ? pls

rich adder
#

🤦‍♂️

ebon peak
#

what now

rich adder
#

you're showing the same image with 0 new information

naive pawn
#

you aren't giving us any info to work with at all lmao

rich adder
#

whatya think?

ebon peak
#

ohhhhhhh

#

i just opened i this video and he said to open the demo and i will work or somthing

#

this but it gave me this error

#

that i showed u

rich adder
#

what good is a premade asset if you have no idea what to do in the edtior

ebon peak
#

i just what to do a third person shooter

pulsar tapir
#

How I can made for my game a exit system?

rich adder
pulsar tapir
#

Esc + exit

rich adder
#

explain what that means

gusty swallow
#

I want to implement momentum based dashing into my game, can you guide me in the right direction on how to make that work? I'm also using the unity character controller.

pulsar tapir
#

Idk if i explain my self well

gusty swallow
#

thank you nav soo helpful

polar acorn
gusty swallow
rich adder
# gusty swallow thank you nav soo helpful

I mean..not sarcastically its been asked over and over and surely you can find many resources on this, its not something you can just explain in a discord message.. its literally an entire system w lots of math involved lol

earnest wind
#

guys, i need some help, how can i make the sliders here "predict" the color based on what the combination is? Something like how unity works?

i already have the shaders all set up, JUST 2 COLOR INPUTS , all i need is just to calculate the colors, how would i begin?

naive pawn
#

it's a gradient - for example on red, it's (0, G, B) to (255, G, B)

#

taking the current values of green and blue

earnest wind
gusty swallow
rich adder
gusty swallow
#

ok thank you man

sweet bough
#

Why does my camera rotate a bit even when its rotation is 0?

using UnityEngine;

public class TeleportTrigger : MonoBehaviour
{
    public Transform targetLocation;
    public string playerTag = "Player";
    public GameObject ObjectToActivate;
    public bool invertRotation;

    private void OnTriggerEnter(Collider other)
    {
        if (!other.CompareTag(playerTag)) return;



        other.transform.position = targetLocation.position;

        var look = other.GetComponentInChildren<FirstPersonLook>();
        if (look != null)
        {
            float currentYaw = look.transform.eulerAngles.y;
            float newYaw = invertRotation ? currentYaw + 180f : currentYaw;
            look.SetYaw(newYaw);
        }
        else
        {
            Quaternion targetRot = other.transform.rotation;
            if (invertRotation)
            {
                targetRot = targetRot * Quaternion.Euler(0, 180f, 0);
            }
            other.transform.rotation = targetRot;
        }

        if (ObjectToActivate != null)
            ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
    }
}
golden notch
#

Should I get Altaruna or try to do my own networking thing?

eager spindle
golden notch
#

not sure, i don't know any other networking solutions

#

i like that it's free for most things

wicked fiber
#

does anyone know why this isnt working?

#

cam.transform.position.z = -10;

rich ice
#

gonna need more details. were there any error messages? is it within an if statement?
it'd help if you sent the !code

eternal falconBOT
wicked fiber
#

my error message was CS1612

#

but I defined the GameObject here

#

cam = Camera.main;

ivory bobcat
wicked fiber
#

Give me a sec

#

im not intelligent

#

theres some other stuff too

ivory bobcat
#

For example: cs var position = cam.transform.position; position.z = -10; cam.transform.position = position;The position property returns a copy of the position Vector3 so modifying it doesn't have any effect on the actual position. In fact, it's a value only and not a variable thus why you should be getting an error about modifying a value and not a variable or something.

wicked fiber
#

ok thanks

#

camPOS = cam.transform.position;
camPOS = transform.position;
camPOS.z = -10;
cam.transform.position = camPOS;

#

Is that better?

#

wait nvm I got it

#

thanks again

ivory bobcat
wicked fiber
#

Yeah, I realized that after I sent it. Sorry

unique lantern
#

Who can help me solve this problem?Is this a lost map?

#

As a beginner, I don't know much about it. I checked the relevant documents, and there are maps in them, but I still don't know how to solve this problem. I hope to get your help

north kiln
sleek bone
#

Hello, I was going through this reference https://docs.unity3d.com/6000.1/Documentation/ScriptReference/MonoBehaviour.html and found this: (Image 1- Awake highlighted text). Here it says Awake is called when the script is enabled. However when I put it to test, so I created a test script with Awake function and disabled the script component, while the gameobject is active. Awake is getting called even when script component is disabled. (Image 2 - Unity editor, look at inspector, TestScript is disabled, and Awake being called in Console.)

Now my question is, how can Awake be called if the script component is disabled?

wintry quarry
cosmic dagger
sleek bone
sleek bone
wintry quarry
# sleek bone Before playing the game in Inspector

From the docs:

Unity calls Awake on scripts derived from MonoBehaviour in the following scenarios:

The parent GameObject is active and initializes on Scene load
The parent GameObject goes from inactive to active
After initialization of a parent GameObject created with Object.Instantiate

ivory bobcat
#

Not sure why "enabled" is written in the description as it'll load without the script being enabled.
Probably something to be edited.

wintry quarry
#

Yeah it's definitely a bit vague

#

As is this "parent GameObject" concept

sour fulcrum
sleek bone
sour fulcrum
#

its weird that its seperate from those 3 rules but it totally does consider script enabled afaik?

cosmic dagger
ivory bobcat
#

I'm assuming it's meant to be something like

Unity calls Awake when script instances are loaded
Unity calls Awake on scripts derived from MonoBehaviour in the following scenarios:
...

cosmic dagger
#

Awake is only affected by the GameObject's active state . . .

sour fulcrum
#

if thats true that doc just outright lies then lol

cosmic dagger
#

It wouldn't make sense because if you only have an Awake method, you cannot enable or disable the script, so how could it be affected by that?

sleek bone
sour fulcrum
ivory bobcat
cosmic dagger
cosmic dagger
sour fulcrum
clear juniper
#

the enabled flag appears when you use any one of the unity magic methods, awake included

sour fulcrum
#

You are right though, just tested it. I think that doc needs to be changed

#

Unity calls Awake when an enabled script instance is being loaded. is incredibly misleading

cosmic dagger
sour fulcrum
#

its kinda like saying "fire will burn any alive person"

#

like yes that is true

#

but fire absolutely burns dead people too

clear juniper
sour fulcrum
#

didnt pop for me until update

clear juniper
#

huh

sour fulcrum
#

im assuming the rules apply to start too so it only really shows up for update

sleek bone
#

Can you try on a empty gameobject?

cosmic dagger
#

It's always been like that for me. I'm currently on 2022.3 . . .

clear juniper
#

works on my machine lol

sleek bone
#

Same, i'm also on 2022.3.40

clear juniper
#

I'm on unity 6, maybe it changed then

cosmic dagger
clear juniper
#

I ditched 2022 as soon as 2023.1 came out

sour fulcrum
#

why are you saying gameobject

#

thats a dif thing?

clear juniper
#

I tried it for a game jam and the new Awaitable class was too good to live without

#

death to coroutines ✊

cosmic dagger
sleek bone
clear juniper
#

async/await is the same but better in every way 🙂

ivory bobcat
#

I'm not on the latest Unity 6 but perhaps it may just be with the current latest release UnityChanThink

#

Relative to the enable component checkbox and Awake

clear juniper
#

instead of

IEnumerator WaitForThing ()
{
   yield return new WaitForSeconds (1);
   Debug.Log("aaa");
}

void DoSomething ()
{
    StartCoroutine(WaitForThing);
}
```it is now
```cs
async void DoSomething ()
{
   await Awaitable.WaitForSecondsAsync(1);
   Debug.Log("aaa");
}
``` no more StartCoroutine, you don't have to be on a monobehaviour (or using a singleton runner) for everything you want to happen over time
#

and you can use async methods in await

#

and you can return values

sour fulcrum
#

re: not using monobehaviours, do all the old things that needed coroutines work for that too?

clear juniper
#

and it has cancellation token support, so you can cancel them

ivory bobcat
blazing junco
#

Btw what would be a good channel to ask this in?

clear juniper
sour fulcrum
clear juniper
#

if you use the Awaitable class it's all on the main thread

#

unless you explicitly call BackgroundThreadAsync

sour fulcrum
#

I'd say that's a notable con but still excited to mess with that eventually

ivory bobcat
north kiln
#

Only if you use the specific API for doing it; which you just wouldn't do

clear juniper
#

it's a little bit extra sure

#

but the benefits vastly outweigh that imo 😂

#

and coroutines are still there if you enjoy putting StartCoroutine everywhere 😉

north kiln
#

you would use the destroyCancellationToken if you already had a MonoBehaviour

clear juniper
#

oh wow I didn't even know that was there

#

that's excellent

#

yeah in that case all you need to do is cs await Awaitable.WaitForSecondsAsync (destroyCancellationToken);

#

(or any of the other awaitable methods)

#

this one feature alone made 2023/6 worth the upgrade 😂

#

I can't tell you how much I hated having wrapper methods that just StartCoroutine a different method, and/or a singleton to manage them for when I needed them in a static or plain C# class

north kiln
#

I can't say async/await is easy for beginners sadly, it's very easy to make mistakes that silence exceptions or leak your tasks into edit mode

clear juniper
#

tasks shouldn't leak into edit mode if you use awaitable, right?

#

they don't for me any more

north kiln
#

but once you get past those few things it opens up into being able to do practically anything

clear juniper
#

but yeah, that's valid

north kiln
#

I have no idea, I use UniTask

#

Awaitable had a bunch of weird bugs and stuff last time I touched it

clear juniper
#

I think they're ironed out now, the only thing that is missing is WaitForSecondsRealtime really (and you can work around that)

north kiln
#

I would presume it would still run across the playmode barrier

clear juniper
#

if you use Awaitable, they are correctly cancelled when leaving play mode 🙂

#

at least on Unity 6 and 6.1

dim berry
#

im currently using the default input axis controller for my cinemachine camera, but am running into an issue with disabling/enabling certain action maps. because im using a generated class and creating an instance of my input action asset, disabling and enabling those action maps dont end up affecting the input for my cinemachine camera. i was wondering if there was a way for my input controller to reference the input action instance. the input action instance is created in an input reader scriptable object.

copper crest
#

Hey, i know this is gonna sound REALLY Dumb but i recently got into Coding and am trying to make a Guessing Game... Can someone Help me find a Good Tutorial For How Do Input Fields Work? I Cant Find Any

wintry quarry
copper crest
#

Ive tried multiple times trying to get the text from the field and checking it, like a code system but it runs the debug for when its wrong, even though i write the correct Answer

wintry quarry
#

and your debugging attempts

copper crest
#

Okay

#

Wait A Sec

rich ice
#

btw, make sure to keep this in mind
!code

eternal falconBOT
magic crown
#

Hey i have a small problem i'm trying to make a kind of active ragdoll using configurable joint and i'm doing this

    void Update()
    {
        for(int i = 0; i < ragdollBody.Length; i++)
        {
            ragdollBody[i].targetRotation = animatedBody[i].localRotation;        
        }
    }

The way this works is the ragdoll set the target rotation to the one of the animated body
and everything work right until i rotate more than 2 axis cause then instead of matching the rotation it rotate differently.

I don't know if it's using quaternion or something else but i really need some help to make this match the rotation perfectly

median hatch
#

does anyone know when unity's summer sale is?

ivory bobcat
magic crown
#

wait i'm gonna make a video

magic crown
#

And i have a guess why it do that but i tried so many thing and it just doesn't work, tried using euler angles tried changing the anchor which change the outcome but never go as wanted

#

I guess it must be using quaternion but it's such a bitch to use that i'm gonna go crazy

ivory bobcat
#

So, can you describe how it rotates differently?

magic crown
#

It's shown on the video, it rotate fine on the x axis and the z axis but once i rotate the Y axis it just turn based on the world Y if that make sens

#

Wait shit i found something When i turn the Y rotation it change the rotation for all of them

#

and i believe the configurable joint don't like that at all

ivory bobcat
#

So, I'm not able to understand the video at all. Given the code, I'm going to assume ragdoll is a list of Animator components and that you're assigning the target rotation of each Animator instance the value specified by some local rotation (likely the object you're directly moving in the scene/video). Maybe serialize two lists of quaternions/eulers and verify if the data truly matches (they likely should, minus root motion physics etc)

magic crown
#

Well that the full code

    [SerializeField] ConfigurableJoint[] ragdollBody;
    [SerializeField] Transform[] animatedBody;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        for(int i = 0; i < ragdollBody.Length; i++)
        {
            ragdollBody[i].targetRotation = animatedBody[i].localRotation;        
        }
    }
#

I'm just taking the transform of the body i want to match and the configurable joint of the ragdoll and telling it to match

#

And i do that for all of my body part in order

stuck field
#

Do you have the "Configured In World Space" option enabled on your joint? If not, you should use world space position, then translate it to local space of the joints transform, or you could try enabling it, and directly using position, but this would mess up if the 2 weren't in the exact same position, but it's a test you can run to figure a bit more out about the problem

magic crown
#

Wait it's not activated but i'm gonna test

magic crown
magic crown
#

thanks

stuck field
#

You'd use it on the joint transforms, just to clarify

magic crown
#

Well using in on the joint transform doesn't change anything

#

but i'm gonna try it on the other transform

#

You know what for now i'm just gonna stop all of that It's been multiple day of barely sleeping trying to get that shit out of my mind i can't anymore

#

need some rest

#

but atleast i have some clue on what's the problem so thanks a lot dude

eager scarab
#

at the start should i keep using a game engine or is it better to get a feel of the language to fully code it all and not rely on an engine (i know the basic fundamentals of coding, so understanding isnt a problem to a certain extent)

eager spindle
eager scarab
#

just asking cause that could apply to both options

frosty hound
#

Going into any multi-disciplinary skill with the existing knowledge and experience is obviously a benefit, that's just common sense.

It's not mandatory either.

#

There's no should or should nots. Whether you work on an individual skill first or simultaneously doesn't really matter and is unique to each person.

dense summit
#

hi everyone- is there any one knows about web request visual scripting- this is my first part of script and I should see my backend messages in the console . but I can not see

rich ice
polar acorn
# eager spindle theres people in this discord that would disagree with me but I feel like its im...

I don't think you'd find many people here who think learning programming in any capacity wouldn't be helpful before starting Unity. Hell, even learning something like COBOL before starting Unity would help. The hardest part of programming isn't the language it's having an intuitive sense of control flow, understanding procedural logic, and how to split a task into smaller chunks, which you could learn in basically any language.

eager spindle
#

big yikes

polar acorn
#

It's not necessary, but it is by no means a bad idea

modern meteor
#

wsg guys, just started using unity today, can someone teach me how it works or smth

queen adder
#

Hello! I'm new to unity, and I got into coding cause I want to be a game developer, I've tried different coding language, most recently, I use ActionScript 3.0, now I am switching to unity, my goal is to create a "gacha life like" game, a character creator/customization game, I tried a tutorial online, but failed, the asset does not switch, nor does the asset switch color like in the tutorial, do any of you know how? Or like know tutorials I can source else where besides youtube?

modern meteor
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

modern meteor
eternal needle
queen adder
eternal needle
sage mirage
#

Hey, guys! I was wondering how I am supposed to rotate a game object to a specific point/angle? Is there method or something?

#

I am currently working on a horror game and I want to rotate a crucifix game object to a specific angle and then to stop rotating. I think you have seen that in horror games.

naive pawn
#

and then you can slerp towards the resulting quaternion

#

or perhaps smoothdampangle before the euler

#

a lot of ways to go about this

sage mirage
#

Probably?

#

I mean in order to create this smooth rotation and then to stop.

naive pawn
#

well depends on how exactly you want it to go, smooth is pretty broad

#

but that's the idea, yes

#

(perhaps get it working before making it look good)

wicked fiber
#

does anyone know why my enemy isn't moving to the player? public class BaseEnemy : MonoBehaviour
{
public float MaxHP;
public float HP;
public float MoveSpeed;

private Rigidbody2D rb;
private GameObject player;
private Camera cam;
public float dist;

// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
    rb = GetComponent<Rigidbody2D>();
    cam = Camera.main;
    player = GameObject.FindWithTag("Player");
    HP = MaxHP;
}

// Update is called once per frame
void Update()
{

    if (HP <= 0)
    {
        Destroy(gameObject);
    }
    if (HP > MaxHP)
    {
        HP = MaxHP;
    }
}

void FixedUpdate()
{
    GetDist(player, gameObject);
    Vector2.MoveTowards(transform.position, player.transform.position, MoveSpeed * Time.deltaTime);

    if (dist <= 5)
    {
        
    }
    if (dist >= 10)
    {
        transform.position += (MoveSpeed * Time.deltaTime * transform.forward);
    }
}

public void TakeDamage(float damage)
{
    HP -= damage;
}

private void GetDist(GameObject Object1, GameObject Object2)  
{
    dist = Mathf.Sqrt(Mathf.Pow(Object1.transform.position.z - Object2.transform.position.z, 2) + Mathf.Sqrt(Mathf.Pow((Object1.transform.position.x - Object2.transform.position.x), 2) + Mathf.Pow((Object1.transform.position.y - Object2.transform.position.y), 2)));
}

}

eternal falconBOT
wicked fiber
#

ok gimme a sec

naive pawn
#

hey btw Vector3.Distance exists

#

the math.. seems to be wrong though

#

that MoveTowards also isn't doing anything

wicked fiber
#

Yeah, IDK why

naive pawn
#

because you aren't doing anything with it

#

also, you have an rb but you're trying to modify the transform

wicked fiber
#

Vector2.MoveTowards(rb.position, player.transform.position, MoveSpeed * Time.deltaTime);

#

Is that better?

#

or should I move it somewhere else

polar acorn
#

You still aren't doing anything with the result

naive pawn
#

MoveTowards doesn't do any physical moving

#

you're just computing the value moved towards the other value

wicked fiber
#

rb.position = Vector2.MoveTowards(rb.position, player.transform.position, MoveSpeed * Time.deltaTime);

#

oh..........

#

whoops

naive pawn
#

why not just use the rb

wicked fiber
#

I fixed that up there

naive pawn
#

setting position does teleportation, not great for doing physics

naive pawn
#

you can just set a velocity pointing to the player

wicked fiber
#

Ok, thanks for the help!

nimble apex
#

i want verification on my code, simply "is this good?"

this is a join request UI that update itself using server data and epoch, with this workflow:
received join request -> 10 second wait(keep updating UI) -> timeout -> deny requests

-> calling

Init(serverEvent evt){
     ...
StartCoroutine(UpdateUI(evt.Time.AddSeconds(CommunicationConstants.JoinRequestDuration)));
}

-> function itself
    private IEnumerator UpdateUI(DateTime endTime)
    {
        while (DateTime.Now < endTime)//localtime
        {
            //updating UI

            yield return new WaitForEndOfFrame();
        }

        UniTask.Action(async () =>
        {
            await SendMsgToPlayer();//network action
        }).Invoke();
        
        Destroy();
    }
#

evt.time is server epoch , so its basically epoch + 10 seconds

naive pawn
#

don't use WaitForEndOfFrame for that

#

if you want to wait a frame, you can just do yield return null;, but for simple checks like that you could also condense it into WaitWhile or WaitUntil (for potentially cleaner code, depending on what you feel is clean)

nimble apex
#

ohhhh lemme try it

#

ty 👍

grand snow
#
UniTask.Action(async () =>
        {
            await SendMsgToPlayer();//network action
        }).Invoke();

This is pointless

nimble apex
#

looks like waitwhile is new stuff

grand snow
#

you can just not await SendMsgToPlayer()

nimble apex
naive pawn
grand snow
#

use .Forget() to make sure exceptions are logged

#

MyThing().Forget();

nimble apex
#

i removed the action layer, lets hope it doesnt become too expensive lol

grand snow
#

there is no perf difference

nimble apex
#
sendMsgToPlayer().Forget();```
#

it become like that now

grand snow
#

the Forget ensures exceptions get logged by un awaited UniTasks

#

the old method probably did the exact same so dw about it

nimble apex
#

ty 👍

nimble apex
#

gonna rewrite them all

grand snow
#

yea probably best 👍

#

try to use async methods when working with async code too, its hard to use coroutines and async together.
Unitask does offer things to let you execute and await a coroutine. Other way around is hard

nimble apex
#

which must return void

#

i do have legit tasks that send stuff over network

#

under unitask

grand snow
#

trival to overcome:
button.onClick.AddListener(UniTask.UnityAction(AsyncFunc));
or
button.onClick.AddListener(() => AsyncFunc().Forget());

#

same problem exists with coroutines so either way its easy to solve

nimble apex
#

i just gonna do forget

#
        accept.onClick.AddListener(() =>
        {
            CommunicationManager.Instance.SendMsgToPlayer().Forget();
            Destroy();
        });```
grand snow
#

yea thats one of the many solutions

velvet dawn
#

does anyone knows about lighting in unity here?

frail hawk
velvet dawn
#

alread did , no reply 😅

naive pawn
#

you're not more likely to get a reply here

velvet dawn
#

i see

grand snow
#

UniTask delay/wait functions can be given a cancellation token as an arg

#

I dont understand the issue if there even is one

nimble apex
#

ok then this should be fine

nimble apex
# naive pawn it was added in 5.3
private IEnumerator UpdateUI(DateTime endTime)
{
    yield return new WaitWhile(() =>
    {
        //update UI
        return DateTime.Now < endTime;
    });
    
    CommunicationManager.Instance.SendMsgToPlayer().Forget();
    Destroy();
}```

for me it does look better , ty 👍
#

EVERYTHING WORKED 😭

lofty sequoia
naive pawn
nimble apex
bright zodiac
nimble apex
#

i will optimize it with the way that chris taught me lol , should be better then

naive pawn
#

they aren't that different

nimble apex
#

im now fixing other errors

grand snow
#

something something wait for time to end in a better way

bright zodiac
#

no no, the lambda will capture the variable there.... if you're fine with closures then go for it

hushed hinge
#

https://paste.mod.gg/uxrbwcxftcnv/0

I do have a little problem, and that is with the MuonManager like i do have it on Don'tDestroyOnLoad
But however when i start the world scene, it starts at "0/12" despite already rescued a muon object, when i got back to the stage and see that one muon object already been rescues, and when finishing the game, the muoncounter went back up to "1"

how do i that the number start at the already rescued muon objects?

forest wolf
frail hawk
#

not 100% sure but i think it is happenig because you got the DontDestroyOnLoad inside the if statement for the singleton, you might want to try it out outside

forest wolf
hushed hinge
hushed hinge
forest wolf
#

No, no - slightly different. Keep the DontDestroyOnLoad but put it before your if:

// put it here
if (Instance != null)
{
// not here
}

hushed hinge
bright zodiac
# naive pawn they aren't that different

they're different in many ways. the delegate passed for waitWhile there got fixed overhead for creating and invoking (call vs callvirt). also closures in general is evil as they will make copies in memory

forest wolf
hushed hinge
frail hawk
#

if you want to share that value between scenes simply create a static c# class which you can access easly

forest wolf
hushed hinge
forest wolf
#

Yep, that's expected "DontDestroyOnLoad" won't help with that. It still resets the state when you 'play' the game.

#

You will need to use scriptable object for that

hushed hinge
forest wolf
# hushed hinge so should i create a new script or?

You need a new script that will extend ScriptableObject instead of MonoBehaviour, it needs to have a special attribute [CreateAssetMenu], then you can create an instance of it in your assets window. Then in your actual script where you count the values you need the reference to that scriptable object and you drag and drop it in the inspector. You can have a look here for a small introduction to scriptable objects: https://www.youtube.com/watch?v=IxxsROBNA04

Hello Fantastic People! Ready to elevate your Unity game development skills? Today, we're diving into the magic of Scriptable Objects. This tutorial is your guide to decluttering your scripts and injecting flexibility into your game design. Learn how to craft configuration files that minimize script variables, perfect for managing properties acr...

▶ Play video
#

the use case is slightly different, but the main idea is shown there. The only thing is - if you want to release the game you also need to store the information and load it (in a file or player prefs)

echo cradle
#

!code

eternal falconBOT
hushed hinge
chrome apex
#

I have a stupid question. I know the Vector3 position my hand needs to move to.

I need to know where each finger will be before the hand reaches that position.

Can I do:

"Vector3 fingerOffsetFromHand = fingertip.position - handTarget.position;"

and then:

"Vector3 predictedFingerTipPos = newHandPos + fingerOffsetFromHand;"?

is this it?

wintry quarry
#

if there is any rotation at all, we'll need to account for that separately

chrome apex
wintry quarry
chrome apex
#

yes

wintry quarry
#

then you would do something like this:

Vector3 fingerLocalPos = fingertip.localPosition;

// newHandPosition needs to be a world-space Vector3 position
// newHandRotation needs to be a world-space Quaternion representing the final rotation of the hand
Matrix4x4 finalHandMatrix = Matrix4x4.TRS(newHandPos, newHandRotation, handTarget.lossyScale);
Vector3 finalFingerPosition = finalHandMatrix.MultiplyPoint(fingerLocalPos);```
sweet bough
#

Why does my camera rotate a bit even when its rotation is 0?

using UnityEngine;

public class TeleportTrigger : MonoBehaviour
{
    public Transform targetLocation;
    public string playerTag = "Player";
    public GameObject ObjectToActivate;
    public bool invertRotation;

    private void OnTriggerEnter(Collider other)
    {
        if (!other.CompareTag(playerTag)) return;



        other.transform.position = targetLocation.position;

        var look = other.GetComponentInChildren<FirstPersonLook>();
        if (look != null)
        {
            float currentYaw = look.transform.eulerAngles.y;
            float newYaw = invertRotation ? currentYaw + 180f : currentYaw;
            look.SetYaw(newYaw);
        }
        else
        {
            Quaternion targetRot = other.transform.rotation;
            if (invertRotation)
            {
                targetRot = targetRot * Quaternion.Euler(0, 180f, 0);
            }
            other.transform.rotation = targetRot;
        }

        if (ObjectToActivate != null)
            ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
    }
}
#

(invert rotation is disabled)

naive pawn
wintry quarry
sweet bough
#

no matter if the rotation is 0 or any other number

wintry quarry
#

Although it's unclear what this "FirstPersonLook" is and how it works

#

so it could be a problem in there

#

I would also really avoid dealing with euler angles in this way, it's bound to lead to sadness and pain

chrome apex
wintry quarry
stiff sky
#

hey, im attempting to "glue" my player mesh to a moving platform that is also slightly rotating around (ship deck), however attempts to simply parent when collision detected merely result in the player mesh rotating with the buoyancy (as in, doing frontflips) and also not keeping the same velocity as the ship while moving

#

one of my friends gave me this code, however its old and doesn't appear to be working

teal viper
stiff sky
#

compiles properly, no errors, just doesn't work. player doesn't acquire ship's velocity, which leads to them flying off the back

teal viper
#

You just need to refine it

wicked fiber
#

What script should I use to make an rb move in it's faced direction?

sour fulcrum
#

a script that makes a rb move in a faced direction probably

#

you might have to be more specific

wicked fiber
#

A script to add force to an in rb. But in the direction it's facing

#

I'm not sure if that's just LinearVelocity though

sour fulcrum
#

what do you mean "what script should i use"

wicked fiber
#

Like, rb.AddForce

#

or, rb.AddLinearVelocity

#

something like that

sour fulcrum
#

ah ok, thats not what a script is

#

those are functions/methods

wicked fiber
#

whoops

#

I forgot, a script is the entire thing

sour fulcrum
#

addforce is probably what you want yeah, if you do a little light googling you'll find some examples/references that might help you out

wicked fiber
#

ok thanks

faint mural
#

hey guys why can't I save my script into the asset directory it says I need to, but I can't I clicked create and add but it moves me to the file explorer

swift elbow
faint osprey
#

im instantiating enmies in my game via a spawner and i want to let the spawner know when the enemy has died. Im trying to do it via actions but struggling to bind the event considering its instantiated at runtime. any help would be appreciated

swift elbow
sour fulcrum
faint osprey
sour fulcrum
#

well you would bind it during the spawning, no?

#

Spawner

SpawnEnemy()
MyEnemy newEnemy = Instansiate(etc.)
newEnemy.OnDeathEvent.AddListener(OnSpawnedEnemyDeath)

eg.

faint osprey
#

that would work however where would you unbind it in case something got disabled or smth

sour fulcrum
#

When the enemy dies?

#

Or if the spawner dies too i suppose but depending on stuff and things less of an issue

faint osprey
#

can do im just thinking of if the spawner got disabled and the enemy dies it would fire and cause an error

sour fulcrum
#

Why would it cause an error?

swift elbow
#

i assume null ref

faint osprey
#

can do that makes sense

sour fulcrum
#

What are we putting a check on?

faint osprey
#

if spawner is active

sour fulcrum
#

That's not really how events should be used

swift elbow
#

what's wrong with this approach?

faint osprey
#

yeah at that point i might as well just call the function from the enemy

sour fulcrum
#

if you need to explicitly check up on one of the listeners at that point the enemy would just talk to it directly

#

when you say the spawner is disabled, that's not a null ref. do you actually mean disabled or do you mean destroy etc.

swift elbow
faint osprey
sour fulcrum
#

events dont care about things being disabled

#

very little does

faint osprey
#

im using system.action

sour fulcrum
#

system.action doesn't even know things can be disabled

#

it's not a c# concept, thats a unity thing

faint osprey
#

yeah but it can cause memory leaks and that if not unbinded correctly

sour fulcrum
#

Potentially yeah, but that's why I was curious on if you actually meant disable or not

#

because the time to unsubscribe would be whenever you destroy or disable it

faint osprey
#

yeah that makes sense i can unbind at destroy but i wont have access to the action in on disable

sour fulcrum
#

why don't you have access on disable?

faint osprey
#

cause the enemy gets instantiated at runtime

sour fulcrum
#

If your spawner is the thing that creates the enemy im sure it could do a fine job keeping track of where it's at 😄

faint osprey
#

yeah no it can but i wont be able to get the reference from the instantiation and put that in the on disable event

sour fulcrum
#

Why

faint osprey
#

well i mean if its possible i wouldnt know how to do it

#
{
    Vector3 randomPos = UnityEngine.Random.insideUnitCircle.normalized * 12;
    GameObject enemy = Instantiate(m_BaseEnemy, (m_Player.transform.position + randomPos), Quaternion.identity);
    EnemyHandler EH = enemy.GetComponent<EnemyHandler>();
    EH.Initialize(m_ES[difficulty]);
    EH.EnemyDead += EnemyDead;
}```

at the bottom i bind my event so how would i take that so i can unbind that in my on disable
sour fulcrum
#

eg.

private List<EnemyHandler> managedEnemies

SpawnEnemy()
managedEnemies.Add(EH)
EH.EnemyDead += OnEnemyDeath;

OnEnemyDeath(EnemyHandler EH)
managedEnemies.Remove(EH)
EH.EnemyDead -= OnEnemyDeath;

OnDestroy() //OrDisable etc.
foreach (EnemyHandler enemy in managedEnemies)
enemy.EnemyDead -= OnEnemyDeath;

#

bits of this can differ depending on preference and how you wanna handle stuff

faint osprey
#

yeah that works ill keep a constant reference to active enemies and not just at spawn

faint mural
swift elbow
#

in what folder are you trying to create the script

faint mural
sour fulcrum
swift elbow
faint mural
sonic arch
#

so i have a gamemanager which has an array of the components

#

when a button is pressed a component is instantiated and added to the list

#

the components properties are set

#

ive also added for debugging purposes that when the component is instantiated and set it prints its values

#

however its values are unset even after being set

naive pawn
#

gonna need to see some !code

eternal falconBOT
sonic arch
#
// in the main script
void AddObject(int posX, int posY) {
    Obj o = Instantiate(ObjPrefab);
    Obj.SetPosition(posX, posY);
    objList.Add(o)
}

void Start() {
    AddObject(3, 5);
    print(objList[-1].posX);
    print(objList[-1].posY); // outputs 3 and 5 as expected
}

// in the component itself when 
void Start() {
    print(posX);
    print(posY); // outputs 0 and 0 even though it was set
}
#

i thought since it was a reference object I could chagne the fields and have it update elsewhere

naive pawn
#

what if you add a print right after the Instantiate, before the SetPosition

sonic arch
#

its still unset

naive pawn
#

yeah, since it's before the setposition

#

what i'm trying to get at is, the component Start might be running before the SetPosition?

#

i don't remember the flow there but i wouldn't doubt it

hexed terrace
#

I'm pretty sure you're right Chris

Obj o = Instantiate(ObjPrefab); // `Start()` will run
Obj.SetPosition(posX, posY); // this is after
#

No, that sort of stuff isn't allowed here.. and won't be in this channel if it was. Delete and post on 👇 !collab

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

brazen spruce
#

hey, is this code related?
i want to change how the theme of the unity layout looks for me, its currently like some light gray but i want it darker

hexed terrace
#

no, obviously not code 😄

naive pawn
#

preferences > color

hexed terrace
#

preferences -> general

naive pawn
#

actually no both places don't let you customize the ui color

hexed terrace
#

general is where you swap between light/ dark theme

brazen spruce
#

ok

naive pawn
hexed terrace
#

no they didn't -> its currently like some **light **gray but i want it darker

brazen spruce
#

its already dark for some reason

#

where even is preferences

naive pawn
brazen spruce
#

also im talking about the colors in the engine

naive pawn
hexed terrace
brazen spruce
#

ohh

#

ok

sonic arch
#

the ohject itself

#

is a copy

hexed terrace
#

ok?

sonic arch
#

and that changes to it will affect like that actual object

sonic arch
grand snow
#

No idea if your code example is correct but you do not call a function on your new instance o after Instantiate()

hexed terrace
#

Obj o = Instantiate(ObjPrefab); creates a new instance of that game object with it's own instances of the components

naive pawn
#

they do

naive pawn
#

try opening the debug inspector or logging in Update

sonic arch
#

ive tried checking in update but what happens is

  1. i instantiate the object
  2. i set its values
  3. i add it to the array
#

from the objects script when i access its own properties it is unset

#

but when i am accessing its from the array it is set

grand snow
#

then they are different instances

#

give each new instance a new name to help when debugging

#

if comfortable, use a debugger

naive pawn
sonic arch
grand snow
#

It is a reference

#

you are fucking up somewhere clearly, either the data is set not when you expect or they are difference objects

#

or your function used to set the data is faulty

sonic arch
#

yeah i can see
wait for testing if two instances are the same, can i just use the equality operator?

grand snow
#

yes

#

if not overwritten for the class it should do ReferenceEquals()

sonic arch
#

ohh okok thanks
ill test it out and see

naive pawn
#

you could also change to Debug.Log and add a context to check if the logs are coming from the same object

sonic arch
#

okay ill try that

#

okay so two debug messages from the same object give me one thats set and one thats unset

#

the call with the set value comes from the gamemamnager

#

the unset one is from the object itself

#

as in when i invoke ShowData() from the gamemaanger it works but from the object it is reset

hexed terrace
#

you need to share more !code

eternal falconBOT
sonic arch
#

in the gamemanager:

#

in the plant superclass

#

in the peashooter subclass

#

peashooter derives from plant

#

could it be that due to being inherited, its fields are reset?

hexed terrace
#

Can you just share the entire classes in one of the paste sites..

sonic arch
#

sure

hexed terrace
sonic arch
#

yeah level .cs is the gamemanager
showdata is testposition

#

sorry i thought itd simplify it a bit

naive pawn
#

which logs are showing the value as unset?

sonic arch
#

the log that occurs in peashooter.cs
in update

hexed terrace
#

always?

round glade
#

Hello

hexed terrace
#

I'd imagine it starts off wrong, and then after singleton.plants[tile.posY, tile.posX].SetPos(tile.posX, tile.posY); changes to the right values

sonic arch
#

when the peashooter is instantiated, the first test log is correct (in level.cs, placeplant())

#

but every subsqeuent log is incorrect

round glade
#

Guys can you help me i am really newbie in unity

eternal falconBOT
round glade
#

!ask

eternal falconBOT
naive pawn
#

read the bot message

#

don't just parrot it

round glade
#

I have some silly question

#

Imma send pic

hexed terrace
round glade
#

How fix this

hexed terrace
#

1- Delete that from here.
2- Find the correct channel -> id:browse
3- Do not post a photo (especially such a bad photo like that)
4- Explain wtf "this" is... no one knows your game

round glade
#

I cant find channel for it

#

Its simple that i cant do it

naive pawn
naive pawn
round glade
#

Thanks

sonic arch
hidden marten
#

i want to find the angle between my enemy and my player.... i have a script in enemy for that... how can i achieve it? i also want it to work when the player is higher or lower than the enemy.

        Vector3 vectorToPlayer = -(transform.position - player.position);
        angle = Vector3.SignedAngle(vectorToPlayer, transform.forward, Vector3.up);
        Debug.Log(angle);

will this work?

naive pawn
#

the angle relative to what

#

there's 3 points involved in an angle - a pivot and 2 endpoints

sonic arch
naive pawn
#

your plant is a class, isn't it

#

that's a ref type, it's not gonna be a copy just from assignment

sonic arch
#

but like the plant in the array is basically a copy of the one that is actually instantiated