#💻┃code-beginner

1 messages · Page 102 of 1

minor roost
polar acorn
#

!code

eternal falconBOT
minor roost
polar acorn
# minor roost https://gdl.space/pofepuhice.cs

Your grass condition is impossible. You're running that code if WorldTiles does not contain that point, but then you check if it does. It cannot both contain and not contain that point

minor roost
#

oh

#

how do ichange it

polar acorn
minor roost
polar acorn
minor roost
#

so how do i make it possible

polar acorn
#

You need to think about what conditions need to be true to spawn a grass tile

#

And don't make impossible conditions

queen adder
#

the argument i put into the function is non zero, however after the equation motion * time.deltatime, it returns 0,0,0.

#

why?

minor roost
polar acorn
slender sinew
slender nymph
queen adder
#

no but ill do that

#

hmmm it doesnt return 0,0,0 anymore

#

just extremely small numbers

#

i'll up the amplitude, see if i get results

#

my code works now! thank you all for the help :>

modern seal
#

Everytime I run my build script for dedicated server it changes the settings in the build settings to dedicated server and I have to switch it back to client, any way to no have that happen?

hidden bone
#

How does one fix camera stuttering/jittering?

cosmic dagger
hidden bone
#

the camera sets its position to the player's position in Update()

slender bridge
hidden bone
#

yes the player has a rigidbody

slender bridge
#

track the player in late update and see if it helps

#

it would probably help to post your code for the camera movement and how its situated in your hierarchy.

hidden bone
#

it seems slightly worse, although i may have implemented it incorrectly

#
        transform.position = cameraPosition.position;``` this is the camera follow script
#
    {
        mouseX = Input.GetAxisRaw("Mouse X");
        mouseY = Input.GetAxisRaw("Mouse Y");
         
        yRotation += mouseX * sensX * multiplier;
        xRotation -= mouseY * sensY * multiplier;

        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        camHolder.transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        orientation.transform.rotation = Quaternion.Euler(0, yRotation, 0);
        transform.rotation = Quaternion.Euler(0, yRotation, 0);
        
    }``` and this is the Look script
#

the camera and player are separated

slender bridge
#

im assumming cameraPosition is a reference to your player object ?

hidden bone
#

yes

slender nymph
cosmic dagger
hidden bone
#

i sampled this from some random tutorial a while ago

slender nymph
#

obligatory "use cinemachine"

#

but if you must do your own camera controls for whatever reason, you typically want to move your camera in LateUpdate if it is following something that moves in Update

hidden bone
#

putting the follow script in LateUpdate exarcerbates the issue

cosmic dagger
slender nymph
cosmic dagger
hidden bone
#

alright thank you both, i'll use cinemachine

slender nymph
cosmic dagger
#

A shortcut is placing an empty child GameObject on the target and tracking that instead . . .

hidden bone
#

ok

queen adder
#

how to do a responsive movement like in valorant using add force. Any forcemode I use doesnt seem to make it feel like what it's supposed to (move when a key is held, and stop immediately after not pressing)```cs

    if(!IsGrounded) rb.AddForce(new Vector3(Input.GetAxisRaw("Horizontal"), 0 , Input.GetAxisRaw("Vertical")) * speed, forceMode); // in FixedUpdate
solemn fractal
slender bridge
sterile radish
#

!code

eternal falconBOT
sterile radish
slender nymph
#

what is its value?

queen adder
sterile radish
slender nymph
#

are you sure

sterile radish
#

yes

queen adder
#

problem with this one is that, you wont move at all when speed is low enough (on majority of forcemode)

slender nymph
# sterile radish yes

then you need to be specific about what you are expecting to happen versus what is actually happening

sterile radish
slender nymph
#

show the rest of the code and the inspector for the object

sterile radish
#

do you want the full script?

slender nymph
#

yes

sterile radish
#

okay

slender nymph
#

okay and just to confirm, you are intentionally setting gravityScale to 0 only after your airTimeCounter is greater than airTime?

sterile radish
#

yes

#

well whenever my counter is equal or greator to than my airTime

slender nymph
#

so you want more gravity for the duration of your airTimeCounter? 🤔

sterile radish
#

wdym

slender nymph
#

i mean that gravity scale being 0 is less gravity. so only after your airTimeCounter has reached the value of airTime do you reduce gravity

sterile radish
#

yeah thats right

slender nymph
#

because right now you have normal (or what i assume is normal) gravity for the duration of the airTime which means you fall faster for that duration

sterile radish
sterile radish
slender nymph
#

sure but you never go to 0 gravity until after you pass that airTime threshold

sterile radish
#

oh yeah

#

so should i set my gravity to 0 during the duration of my counter and only set it back to it's og amount when it reaches my airTime value?

slender nymph
#

yes

sterile radish
# slender nymph yes

i still have to tweak some stuff but im glad i found the problem thank you!! :)

queen adder
#

!code

eternal falconBOT
spiral narwhal
#

Could anyone help me with smoothing on a slider? 😅
This implementation is not working at all. I don't really know what I'm doing in Mathf.SmoothDamp -

public class ExperienceView : MonoBehaviour
    {
        [SerializeField] private Slider _experienceSlider;

        private float _currentVelocity;
        private int? _xpUpdateAmount;

        private void OnEnable()
        {
            ExperienceService.Instance.OnXPGained += UpdateXPSlider;
        }

        private void OnDisable()
        {
            ExperienceService.Instance.OnXPGained -= UpdateXPSlider;
        }

        private void Update()
        {
            HandlePotentialXPUpdate();
        }

        private void HandlePotentialXPUpdate()
        {
            if (_xpUpdateAmount is null) return;

            // !! THIS PART !! 

            _experienceSlider.value = Mathf.SmoothDamp
            (
                _experienceSlider.value,
                (float)_xpUpdateAmount,
                ref _currentVelocity,
                10f
            );

            if ((int)_experienceSlider.value == _xpUpdateAmount) _xpUpdateAmount = null;
        }

        private void UpdateXPSlider(int newXPAmount)
        {
            _xpUpdateAmount = newXPAmount;
        }
worldly jolt
worldly jolt
slender nymph
#

that makes it nullable

#

also they are using unity's Slider object

queen adder
#

heres my code,

slender nymph
#

don't multiply your mouse input by deltaTime

queen adder
#

i am trying to make the sway variable give the camera a little sway when it moves on the x axis.

#

however,

#

inside the camsway function

#

when i lerp the sway variable to 0, it gives me a very quick climb down to 0

#

resulting in the camera shaking

queen adder
#

unless youre not talking to me

slender nymph
#

yes, don't do that

queen adder
#

then whoopsies

#

what?

#

should i just

#

take it off entirely

slender nymph
#

don't multiply your mouse input by deltaTime

#

yes, because you should not be multiplying your mouse input by delta time.

queen adder
#

well

#

if i do that the sensitivity goes sky high

slender nymph
#

reduce your sensitivity by a factor of 100

queen adder
#

ok

spiral narwhal
slender nymph
#

you currently have smoothdamp set to take 10 seconds to go from the current value to the end value. but you're also just assigning the current value to the end value every time you change the value

queen adder
#

anyways uhh could i have help with my sway problem

slender nymph
#

what debugging steps have you done

spiral narwhal
slender nymph
#

if that is the intention then why are you using SmoothDamp

spiral narwhal
#

too smoothly transition from one value in the slider to another

slender nymph
#

because _xpUpdateAmount is already equal to _experienceSlider.value

#

ah wait, i think i misread what you are subscribing to

spiral narwhal
#

Mm, perhaps I've got some kind of misconception.
What I think I'm doing is this:

  1. I start with the current value of the slider
  2. I intend to increase it until _xpUpdateAmount is reached
  3. that intermediate step is what I intend to assign to _experienceSlider.value
slender nymph
#

you also need to describe what exactly isn't working. because so far all you've said is that "This implementation is not working at all" which doesn't really say what is wrong

spiral narwhal
#

That's fair, sorry!
I've changed 10f to 1f (one second?) and it incorrectly does this: it slowly updates the slider value, but either it stops too early, or it doesn't use the correct target value (for example 40% is more like 10%)

slender nymph
#

have you printed out the values of the variables you are using or used breakpoints to inspect them to see what is going on?

spiral narwhal
#

No, but I feel like SmoothDamp isn't really what I'm looking for. I'll try a simple Lerp.

queen adder
#

do you manually do gravity if you want to use character controller?

slender nymph
#

if you want to jump, yes. if you don't care about jumping then you can use SimpleMove which applies gravity but ignores any movement along the Y axis

buoyant knot
#

there are lots of times where you want to make sure gravity is just right. like no gravity when standing on a slope, or higher gravity when falling then jumping up

worldly jolt
jagged ridge
#

I am trying to instantiate an object facing the player with a rotation that is lined up. It spawns in the right place but for the Quaternion it won't line to the player's rotation. I've tried the player's rotation which spawns it at an opposite rotation and the Quaternion Inverse which also didn't work.

nova gazelle
#

Hey Together i'm using Netcode für GameObjects and can't Find anything helpful about the following Error. I'm getting it after using the Update() to move something the whole time. Can someone Tell me more?

[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 120, but that trigger was not received within within 1 second(s).

summer stump
somber herald
#

is uv the image texture?

teal viper
#

Uv is an array of vectors per vertex that determine what point in the texture should be sampled at/around each vertex.

#

Uv mapping if you heard about it.

somber herald
#

oh so like uv unwrapping

#

turns that into a uv map right?

teal viper
#

Yes

somber herald
#

so all uv points are 2d

teal viper
#

Yes

somber herald
#

I see ty

sterile radish
#

how do i make the slider for my float in the inspector have a step of 1

rich adder
sterile radish
#

oh yeah

#

ty

#

what if i wanted the step to be 0.5 tho?

rich adder
#

you'd probably have to make a custom propdrawer

dawn rampart
#

why is isGrounded always true?

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UIElements;

public class PlayerMovement : MonoBehaviour
{
    public GameObject player;
    private Rigidbody2D rb;
    private Animator animator;
    private SpriteRenderer spriteRenderer;
    private PlayerControls playerControls;
    public float moveSpeed = 10f;
    private float horizontalInput;
    public float jumpForce = 10f;
    bool isGrounded = true;
    public bool canFlipX = true;
    public int jumps = 0;

    private void Awake() 
    {
        playerControls = new PlayerControls();
    }

    void Start()
    {
        player = this.gameObject;
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    void Update()
    {
        isGrounded = Physics2D.Raycast(transform.position, Vector2.down, 0.1f);
        rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
        Debug.Log(isGrounded);

        Vector2 movementInput = playerControls.Movement.Walking.ReadValue<Vector2>();
    }

    public void Move(InputAction.CallbackContext context)
    {
        horizontalInput = context.ReadValue<Vector2>().x;
        rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
    }

    public void Jump(InputAction.CallbackContext context)
    {
        if (context.performed && jumps < 2)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            jumps++;
        }
        else if (isGrounded)
        {
            jumps = 0;  // Reset jumps when grounded
        }
    }
}
summer stump
dawn rampart
summer stump
dawn rampart
summer stump
#

The layermask that you pass into the raycast is just the layers you want it to interact with
You DON'T want it to interact with the player, and probably not default or other things like that

dawn rampart
summer stump
#

Also, you are starting the raycast from the center of the object and going down .1f

dawn rampart
summer stump
#

Ok good. The issue is probably that the raycast simply doesn't reach

#

You can make an empty object and make it a child of the player, then move it to the feet. Use that as the origin of the raycast

dawn rampart
shrewd arrow
#

does anyone know how to code random side to side movement in c# like gelli fields, but it doesnlt move towards food

summer stump
queen adder
#

Hi all i need some help with 2 problems i got.

  1. I have some "pets" in my game. They are on their own scene and they basically just walk around in an fenced off area. I want them each to drop say a 💩 (turd) every hour or so (but not all at once).
    How can i make them drop that turd that will be a button in the game so when the player clicks on it they will get a small reward of coins, gems or pet food. Im stuck y'all. I tried google with no luck.

  2. In my main game where the player does their main gameplay which is kill monsters. I have a panel that pops up when the player levels up to tell them they have leveled up and to give them a rewards. Thats all working great. But i want to gameplay in the background to pause/freeze while they are in the level up popup. I have tried setting timescale to 0 while the panel is open and back to 1 when the panel closes but the background gameplay still doesnt pause. Also i tried making a public enum GameState. I added move and pause to it. Then in my start i i said currentState = GameState.move;
    Then when the panel opens i made the GameState to pause.
    But that also doesnt seem to pause the game.
    The only time it pauses is if i click on the GameState button on my script in the inspector. Like only if i click that button to choose what state i want. But it doesnt matter what state i choose the game still keeps running in the background.

shrewd arrow
#

I ended up with this:

#

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

public class RandomMovement : MonoBehaviour
{
public float speed = 5f;
public float changeDirectionInterval = 2f;

private float nextDirectionChangeTime;
private Vector3 targetDirection;

void Start()
{
    ChangeDirection();
}

void Update()
{
    // Move the object in the current direction
    transform.Translate(targetDirection * speed * Time.deltaTime);

    // Check if it's time to change direction
    if (Time.time >= nextDirectionChangeTime)
    {
        ChangeDirection();
    }
}

void ChangeDirection()
{
    // Generate a random direction (side-to-side movement)
    float randomX = Random.Range(-1f, 1f);
    Vector2.x = Vector2.x + randomX;
}

}

#

but there is an error:

#

Assets\Scripts\SlimeMovement.cs(34,21): error CS0120: An object reference is required for the non-static field, method, or property 'Vector2.x'

summer stump
shrewd arrow
#

It is supposed to change the x by -1 to 1 based on a random variable

#

I meant to use Vector2 to do that, I am very new

summer stump
#

Well Vector2 is a type.
So you would make a variable that IS a vector2:

Vector2 newDirection;

newDirection = new Vector2(randomX, 0);
#

Something like that

shrewd arrow
#

ok, thx, ill try that

summer stump
#

Also, the error says SlimeMovement, but the class says RandomMovement.
The file name and class name need to be the same

last grove
#

can someone please explain to me what coroutines are and why I should use them like I'm 5 years old

#

I can't find any resources that make sense

summer stump
#

Normally methods will run until they complete, and the computer can't do anything else until it DOES complete

last grove
#

ok

#

so like you start a coroutine and then you could have it stop until a value is correct and then run again?

summer stump
last grove
#

gotcha

#

thanks

summer stump
#

No prob.

It goes deeper for sure. But I just wanted to keep it simple like you wanted

last grove
#

I appreciate that

#

Im writing a gun system right now and I have to use them for the first time

chilly vigil
#

help how can i fix this

slender pebble
#
    private void Update()
    {
        body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);

        if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            body.velocity = new Vector2(body.velocity.x, speed);
            isGrounded = false;
        }

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            isGrounded = true;
        }
    }
#

this feels a little slow

#

I feel a delay when I touch the ground, it takes a little while for isGrounded to be true

acoustic arch
#

https://hatebin.com/fcnnfdnkln
i feel like i might be being a major dum dum, but i cant find out why the camera is always defaulting to being turned at a 0,0,0 rotation whenever i start the game

#

even if i change it itll switch it to 0,0,0

#

will locking the cursor cause that?

#

oh i see, its from line 42 updating its rotation to it nvm

ivory bobcat
# acoustic arch even if i change it itll switch it to 0,0,0

To retain initial inspector changes, you could do something like..cs void Start() { //locking the cursor to not be visible Cursor.lockState = CursorLockMode.Locked; var initAngle = transform.localEulerAngles; mouseX = initAngle.x; mouseY = initAngle.y; }

summer stump
# chilly vigil help how can i fix this

In ChangeCircle, line 35, you wrote Input.something but you are using the new input system, and that is not compatible under your current settings

If you go to something like Edit > Player there is a "current input mode" or something like that where you can select "both"

autumn briar
#

Does the Start method run when instantiating an object or is it only when clicking play?

chilly vigil
charred spoke
#

It runs when you instantiate yes

summer stump
north scroll
#

hey im coding a simple turret shooting 3d game. Im currently having trouble with enemy collider detection so that the application quits when colliding with the player. This is the function im using in the enemy script.

void OnCollisionEnter(Collision collision)
{
    // Check if the collision is with the player (tagged "Player")
    if (collision.gameObject.CompareTag("Player"))
    {
        // Quit the application to stop the game
        Application.Quit();
    }
}

Currently both player and enemy have colliders (enemy has rigidbody too so i can freeze its rotation as I dont want it to fall over when moving towards the player). The player is tagged appropriately. Not sure whats wrong, ive added a debug as the first thing in the collisionenter function but it didnt even hit that. Ping me if you can help :D

summer stump
#

I assume the Enemy?

north scroll
#

yep

summer stump
#

Application.Quit doesn't work in the Editor by the way, but it not showing the debug means the issue is something else

north scroll
#

yea the only other thing i tried was increasing the collider size of the enemy every so slightly outside of the mesh/capsule itself, although im sure that wasnt the problem. And ok, i will take a look ty

summer stump
#

Maybe something with the rigidbody

bright zodiac
#

it is weird, I know atwhatcost

eternal needle
woven crater
#

how to get a point infront of a gameobject that also accounted it rotation

woven crater
#

neat,ty

dawn rampart
#

do people just enable a hitbox in the animation during attacks or what?

woven crater
summer stump
woven crater
#

yea sorry for ping i was looking and over look it

north scroll
dawn rampart
#

my code isnt working to enable/disable a collider

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

public class PlayerAttack : MonoBehaviour
{
    private Animator animator;
    private PlayerControls playerControls;
    [SerializeField] private Collider2D hitbox;

    private void Awake() 
    {
        playerControls = new PlayerControls();
    }

    private void Start()
    {
        animator = GetComponent<Animator>();
        playerControls.Attack.Attack.performed += Attack;
    }

    private void OnEnable()
    {
        playerControls.Enable();
    }

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

    private void Attack(InputAction.CallbackContext ctx)
    {
        if (ctx.performed)
        {
            animator.SetTrigger("Attacking");
        }
    }

    public void EnableHitbox()
    {
        hitbox.enabled = true;
    }

    public void DisableHitbox()
    {
        hitbox.enabled = false;
    }
}
summer stump
eternal needle
north scroll
rich adder
dawn rampart
summer stump
dawn rampart
rich adder
# dawn rampart

you should def select the animator on the object while you inspect that animator event

#

so you can link the method properly
also make sure there aren't any transition issues like leaving clip early

charred spoke
summer stump
dawn rampart
#

sorry

summer stump
north scroll
dawn rampart
charred spoke
summer stump
rich adder
#

You have to select the object that has the animator

summer stump
dawn rampart
summer stump
summer stump
dawn rampart
north scroll
summer stump
north scroll
#

ive yet to change any default settings when adding the rigidbody component to any game object

summer stump
# dawn rampart

Well, it looks to be select in the dropdown..
I'm not sure sorry.
Animations are one of my weakest subjects

dawn rampart
#

What about the collider

north scroll
summer stump
#

Neither collider is a trigger, right? I would assume not if you aren't falling through the ground

north scroll
summer stump
#

Yep, ok

rich adder
north scroll
#

since im still just learning, i did try messing around with those at first.

#

the trigger i mean

#

but ended up with it off

dawn rampart
rich adder
somber tiger
# north scroll

Can you try including the layer of the object you want to collide?

dawn rampart
somber tiger
#

In the "Include Layers" dropdown

north scroll
#

sry, what do you mean layer

rich adder
north scroll
#

oh ok. Sry but what item from the drop down should I be choosing? Currently its NONE

#

or NOTHING, for include layers

#

AND exclude layer

somber tiger
eternal needle
rich adder
#

and make sure that clip is being hit

#

fix the transitions too make sure they don't skip the event

dawn rampart
queen adder
#

is there a way to determine if a sprite is fully transparent? Like literally empty

north scroll
#

ok I just changed it to the player instead and it seemed to work. How do I go about quitting the game tho? Someone mentioned something about disabling playmode, not sure what that means. I just want the project to stop and the user to have to hit play again to start the game again

#
// Check if the collision is with the player (tagged "Player")
if (collision.gameObject.CompareTag("Enemy"))
{
    Debug.Log("XXXXXXXXXXTESTXXXXXXXXXXXXXXX");

    
    Application.Quit();
}

This doesnt work. And I looked into
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif}

which is what someone else mentioned, but it didnt format correctly and I think the # are read as comments

keen dew
#

It does format correctly, and no it doesn't read it as comments, it grays out the part that doesn't compile in that setup

ivory bobcat
keen dew
#

and the player doesn't play the game in the Unity editor so Application.Quit just closes the game

north scroll
#

and when I ran it it mentioned something about comment or something

keen dew
#

#endif} is wrong. The } must be on the next line.

ivory bobcat
#

Or not be there at all

keen dew
#

oh right, there's one too many

#

and the IDE is not configured

eternal needle
#

after you remove the bracket, you should be able to auto format it with your ide. the code itself should still be indented

north scroll
#

it worked, ty !

eternal needle
eternal falconBOT
worldly jolt
#

Im looking for another beginner to work with on the upcoming IGDB beginners jam. If you are interested or want more info please dm.

eternal falconBOT
worldly jolt
eternal needle
worldly jolt
#

ohh

#

why is that a rule

#

ima just tryna find someone for a game jam thats a stupid rule

slender pebble
#
    private void Update()
    {
        body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);

        if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            body.velocity = new Vector2(body.velocity.x, speed);
            isGrounded = false;
        }

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            isGrounded = true;
        }
    }
#

this feels a little slow
I feel a delay when I touch the ground, it takes a little while for isGrounded to be true

worldly jolt
#

i dont know if this is the issue but creating two new vector2s every single frame is probably slowing your game down a lot

worldly jolt
#

im not sure if you need to say new Vector2 or if you can just go body.velocity.x, speed rather than new Vector2(body.velocity.x, speed

young warren
#

OnCollisionEnter2D runs on a fixed time step because it's physics based. that might be why

#

not sure how much of a delay you feel though

eternal needle
worldly jolt
#

k im beginner also i just thought id see if i could figure it out since its good too learn

worldly jolt
#

im pretty sure atleast. again, im a beginner but from what i understand that is how it would work

quick moon
#

!code

eternal falconBOT
worldly jolt
#

'''cs
deijauhuhfdauh
'''

#

doesnt work

fringe plover
#

!code

eternal falconBOT
fringe plover
quick moon
#
    private void Update()
    {
        if (countdown <= 0f)                    // If the timer reached 0
        {
            if(gameEnd==false)                  // If the game is still going
            {
                 StartCoroutine(SpawnWave());   // Start spawning the waves
            }
        }
        countdown -= Time.deltaTime;
    }
    IEnumerator SpawnWave()
    {
        for(int i = 0; i < Waves.Length; i++)   // Goes throu all the waves
        {
            activeNumber = Waves[i];            // "Budget" of the active wave
            activeMin = Min[i];                 // The minimum spawn value for this wave
            activeMax = Max[i];                 // The maximum spawn value for this wave
            while (activeNumber > 0)
            {
                int random = Random.Range(activeMin, activeMax); // Gets a random number between the min and max spawn value for this Wave
                if (random > activeNumber)                       // Checks if there is still enough wave budget for this spawn
                {
                    int newrandom = Random.Range(1, activeNumber);  // If there isnt enough "budget" it gets a new spawn value within "budget"
                    random = newrandom;
                }
                SpawnEnemy(random);                                // The final spawn value corresponds to the serial number of one of the enemies and spawns it
                yield return new WaitForSeconds(3f);             // Time between 2 spawns
                activeNumber = activeNumber - random;              // Reducing the "budget" by the spawned enemy's value
            }
              yield return new WaitForSeconds(5f);                 //Time between 2 waves
        }
        gameEnd = true;
        Debug.Log("You Won!");
    }

}
```  Guys, this code worked until I commented it, now the time betwen spawns and time between waves doestn work well. They all spawn within like 0,001 sec from the last one.
eternal needle
eternal needle
fringe plover
eternal needle
quick moon
#

Thanks. Its strange tho because it worked before without having that

eternal needle
eternal needle
quick moon
#

Hmmm strange. Strange. But thanks for help

languid spire
quick moon
#

OMG I DID!

#

It was bellow tho

north scroll
#

how can I edit a pre existing prefab? I created an enemy prefab and then continued working on it after trying to implement a score TextmeshproUGUI. Only problem is when I try to drag the text object here, it doesnt let me add it

languid spire
#

you cannot add scene objects to prefabs

fickle plume
rare basin
#

althought the structure looks bad, Enemy shouldn't have references to your UI score text

north scroll
rare basin
#

you instantiate the Enemy, and then assign the referecens via code

north scroll
#

that's not really helpful. I get that as programmers we're all for "critical thinking", but that "via code" is just a useless statement.

I thought that if I was able to publicize variables, I could just drag and drop them in the unity inspector, but it seems I can't do that with prefabs. Imma just look for a way to reference the textmeshgui through start() i guess

rare basin
#

yes you can

#

you just can't drag&drop scene objects to prefabs

#

and as I said, you shouldn't have reference to your UI score text inside Enemy script

#

instead you should have some kind of UI manager, and when the enemy dies, access that UI manager in your enemy Die() function, and change the text

ruby python
#

For scores and the like, maybe look at using a Singleton?

rare basin
#

you should make UIManager (singleton) or ScoreManager (singleton)

#

and when enemy dies access that singleton and increase score, change text, call an event whatever

north scroll
#

new to this, never heard of singleton before

rare basin
ruby python
#

They're incredibly useful.

north scroll
#

ty RCE, much better help than just a google emoji

ruby python
#

tbh, I typed 'Unity Singleton' into google and that was the first result. 😕

rare basin
ruby python
#

Speaking of which.......lol.

I'm having a bit of an issue that I don't really understand. Posting in here cause I'm 99% certain it's to do with the code and no the actual Animation 'segment'.

https://pastebin.com/eJGLGW6E

For some reason, only the backwards and right strafe animations play, and I can't seem to figure out why (Using a Blend Tree), and yes, I know it's horrible code. lol.

fickle plume
prime lodge
#

hello iam making a topdown player controller and this moving script doesnt work

#

i have rigidbody on kinematic

fringe plover
#

set it dynamic

#

it must be dynamic if you want object to move

prime lodge
#

i read that moveposition is best for kinematic

ruby python
#

Not using MovePosition it doesn't (Literally just tried it myself to see if that was the issue on my topdown controller. lol.

#

@prime lodge Could do with seeing all the code if honest.

!code

eternal falconBOT
rare basin
fringe plover
#

sorry didnt know

strong harness
#

SetParticles does not work via script. Did you have similar problems to set particles through script?
I have checked, particle array passes to SetParticles correctly

   var ripplePSInstance = _pool.Get();
                    yield return null;
                    _rippleParticleSystems.Add(ripplePSInstance);
                    ripplePSInstance.transform.position = Vector3.zero;
                    ripplePSInstance.SetParticles(_ripples, rippleCount);
                    ripplePSInstance.Stop();
                    ripplePSInstance.gameObject.SetActive(true);
                    ripplePSInstance.Play();

prime lodge
#

how do i change rotation?????

slender nymph
prime lodge
#

like this?

slender nymph
#

yes, that is better. but of course you're now setting a different axis to 180

fossil gulch
#

x, y, z

#

just hover over the Euler text

#

it'll show you what what is

modest barn
#

I'm getting a constant error in the Console but I don't want to see it anymore. How can I mute individual errors?

slender nymph
#

you could fix the error

slender pebble
modest barn
# slender nymph you could fix the error

It's a store asset and it works perfectly fine, just getting thousands of errors, all the same, that I don't understand because I didn't write the script. It works fine so I don't care to fix it

slender nymph
mellow flint
#

Hi, I'm having a problem with my code and it's driving me crazy
im trying to add +1 to the money every 1 second but for some reason its not working

slender pebble
slender nymph
modest barn
#

Alright, thanks.

slender nymph
chilly moat
#

How do I raycast forward from a transform but with an offset of precisely X degrees towards the right?
Can someone help me figure out that direction ?

mellow flint
slender nymph
#

ah wait, i see the issue. you're creating brand new instances of those objects for each iteration of your loop

mellow flint
#

i create a new instances for a gameobject called Machine and the machine is supposed to add +1 to the money in the GameManager script

slender nymph
#

machine is not a gameobject

#

and you're adding to the money field of Player not gamemanager

#

Player is also not a GameObject or even a component

#

but again, you're creating a brand new instance of Player for each iteration of the loop

mellow flint
slender nymph
#

that makes absolutely no difference to what i have said

timber tide
mellow flint
slender nymph
#

ah yes, another issue. that's super descriptive

slender nymph
#

well you're probably starting the coroutine multiple times. of course you're not providing the full code so that's just a guess 🤷‍♂️

mellow flint
slender nymph
#

do you understand what your code is doing? because it really seems like you're just throwing shit around randomly and hoping it works

mellow flint
#

this shit hurts

#

but yea

#

i think so

slender nymph
#

do you?

mellow flint
#

yep

#

im still new to programming btw

#

so dont expect the best clean code ever

slender nymph
# mellow flint im still new to programming btw

then you should go through some beginner courses to learn what you are doing. and learn how to reference other objects.
because you're still just creating completely separate instances of the Player object that have nothing at all to do with your GameManager or even each other

#

on top of that you're still creating a new Player instance every single frame inside of Update for some unknowable reason

mellow flint
#

okay

#

ty for help

mellow flint
prime lodge
#

i dont know what iam doing wrong but colliders on my character just doesnt work can somebody help me
iam struggling for like an hour

#

and the tile map has tilemap collider

#

he just goes right the the hill

patent compass
slender nymph
patent compass
#
PlayerRigidbody.MovePosition(PlayerRigidbody.position + DirectionInput * PlayerSpeed * Time.fixedDeltaTime);```
prime lodge
slender nymph
slender nymph
#

well it's a good thing that wasn't a reply to you then, isn't it?

prime lodge
#

thanks sooo much

patent compass
#

no on collision as you see the object keeps on going in the opposite collision direction

#

oh. sorry!

slender nymph
#

because you need drag to slow an object down over time

patent compass
#

its not my code, it belongs to a friend. I cant try it out and see. UnityChanOops I thought it was because he was using moveposition instead of rb.velocity. thanks for the help!

ivory bobcat
#

Tell your friend to try it out

patent compass
#

No problem. But my question still stands, is moveposition reccomended over velocity? I thought it causes issues with collisions

ivory bobcat
#

The docs suggest move position for kinematic rigid bodies

patent compass
#

So i was right. he should use velocity since its dynamic

split dragon
#

Hi. I wrote a script: "NoteRead", which allows you to read notes. This script takes the text from another script: "Note". With just the text, everything was fine, and everything worked fine. When I decided to add another font (notes for a change), when I open the sheet, I get an error. I tried to inherit the script: "NoteRead" from the script "Note", but nothing helped. Line: 29
Mistake: ArgumentException: GetComponent requires that the requested component 'FontData' derives from MonoBehaviour or Component or is an interface.
UnityEngine.GameObject.GetComponent[T] () (at <c2d036c16ca64e0eb93703a3b13e733a>:0)
NoteRead.Update () (at Assets/Scenes/General/Скрипты/NtCpRead.cs:29)

eternal falconBOT
slender nymph
split dragon
rare basin
#

how can we know that

#

what is FontData

#

is this a SO?

ivory bobcat
white geyser
#

How can I update the state of properties in a script, from an "Editor" script. When I use "serializedObject.ApplyModifiedProperties();" It works but errors the following:

#

How can I do the same thign without the error?

slender nymph
split dragon
ivory bobcat
rare basin
#

is FontData a scriptable object, non-monobehaviour class or what is it

split dragon
ivory bobcat
#

I'm assuming the stuff on the left hand side of the assignment operation is simply made up and thus the line makes very little sense.

rare basin
#

this is a Text component

#

nothing related to your FontData

#

whatever FontData is

slender nymph
rare basin
#

and Text component is deprecated

#

is FontData something you created yourself?

split dragon
slender nymph
#

yes you can

rare basin
#

of course you can

#

you can do much more things than in deprecated Text component

split dragon
ivory bobcat
white geyser
rare basin
#

so you can access all the Text fields

#

change text, font size etc

#

but you really shouldn't use Text, use TextMeshPro instead

lucid jetty
#

hey im working on a checkpoint system but when i die the boxclider of the checkpoint comes back so i have a invisble box i cant walk trough. + he destroys also my empty game object instead of the cube (spawnpoint) so he also destroy ever single other spawnpoint

https://pastebin.com/Ar9YtE5a

split dragon
split dragon
rare basin
#

no thank you

ebon fox
#

hello
im having a problem with classes.

basically i have a class called "HomeData" inside of another class called "HomeManager".

this i the "HomeData" class:

[Serializable]
    public class HomeData
    {
        public string HomeSize = "Default";
        public string Floor = "Default";
        public string Roof = "Default";
        public string WallTexture = "Default";
    }

the problem is when i do "new HomeData()" it just = "HomeManager+HomeData" for some reason but i want it to be all the data inside of home data so like (HomeSize = Default, Floor = Default) and so on

ivory bobcat
lucid jetty
#

only the collider returns

#

the object is gone but the collider comes back

ivory bobcat
#

Not certain how you're respawning but if it's a reload of the scene, everything should return to normal.

#

Why does it come back? You'll need to tell us. The code provided simply destroys whatever triggered it.

dusty rivet
#

i got a question, why when i change my canvas to screen spcae - camera and try to move a ui element it just goes thousands of positions away from where i told it to

lucid jetty
#

i only having that script

rare basin
#

not overlay

dusty rivet
ivory bobcat
rare basin
dusty rivet
dusty rivet
ivory bobcat
#

Without code, people can't really help you unless it's simply a logical error and a simple one at that.

dusty rivet
#

difficultiesTexts.LeanMove(new Vector2(960, 90 * difficultiesList.IndexOf(selected) + 540), 0.4f).setEaseInOutCirc(); theres the code for when i make it move, and it works perfectly fine when im using screen space - overlay but i want to add post processing to my ui and when i use screen spcae - camera the ui element just disappears

#

i am making a difficulty selection screen

rare basin
#

what is LeanMove

dusty rivet
#

its a function from the LeenTween library

#

for ui animations

rare basin
#

no idea how this function works so can't really help

#

you could easiyl do it with DOTween tho

#

with DOAnchorPosition

warm pawn
#

so Unity says that I cant use && in this example. how else should I tell it to check for both?
https://hastebin.com/share/ekehegaxen.csharp

dusty rivet
slender nymph
ivory bobcat
rare basin
#

for UI elements you need to move it by anchoredPosition

dusty rivet
#

idk if thats the same

slender nymph
eternal falconBOT
lucid jetty
dusty rivet
#

but its weird coz it works perfectly fine with screen space - overlay

ivory bobcat
ivory bobcat
#

I'm also assuming check point and spawn point are the same

lucid jetty
ivory bobcat
lucid jetty
ivory bobcat
#

You probably aren't wanting to destroy the object. This object is also responsible for returning your player to a recent position

#

Looks like a feature request with conflicts of your current system which folks won't normally write/code. But an optional simple solution would be to disable the collider component.

lucid jetty
ivory bobcat
#

I'm not certain since it would seem you're referencing a list of game objects (supposedly check points) as well

#

It would depend on your setup

lucid jetty
#

can i send you my project so you can check on it?

ivory bobcat
#

Just ask your question here with more info and people will consider giving suggestions

cold vigil
#

https://pastebin.com/YGC4UaNY i have an empty video1 object with this script attached to it. the children of the object are canvas with rawimage and videoplayer object with video. by the way, the two videoplayer Video1 and Vide2 are turned off by default because I don't want their audio to be played at the same time. I want video1 and video2 to be played alternately, but the problem is that after 2 videos nothing happens, not even debug messages from my code are displayed, only a black screen. please help

lucid jetty
#

hey im working on a checkpoint system but when i die the boxclider of the checkpoint comes back so i have a invisble box i cant walk trough. + he destroys also my empty game object instead of the cube (spawnpoint) so he also destroy ever single other spawnpoint it also destroys my pickupgun script so when i walk inside the boxcolider of the gun to pickit up the game thinks its a spawnpoint when i fell of the map the game this to uncheck the istrigger .

https://pastebin.com/Ar9YtE5a

brave tapir
#

i think i messed up:

ivory bobcat
# lucid jetty hey im working on a checkpoint system but when i die the boxclider of the checkp...

You've got a lot of random stuff in your spawn manager.. Maybe have a script on the check points and simply let this spawn manager be responsible for respawning - decouple some of the random code. //Spawn Manager Player (Game Object) Respawn Position (Vector 3) Previous Previous Check Point (Check Point script)`````` //Check Point Spawn Manager (Spawn Manager Script) On Trigger Enter Respawn Position equal to this position Respawn Enable Previous Check Point Respawn Previous Check Point equal to this Check Point Disable this component (the Check Point Script)Assuming you're allowing backtracking to previous checkpoints. Stuff done in trigger is an implied interaction on the Spawn Manager reference.

white geyser
slender pebble
#
    public Vector2 boxSize;
#

why can I not see the box size?

#

white outline in the editor (the green lines are the box collider)

timber tide
#

You need to draw a gizmos

slender pebble
#

got it ty

white geyser
slender nymph
white geyser
kindred comet
#

How do I loop through a json

#

none of the tutorials work

frosty hound
#

You've uncovered the great conspiracy

gaunt ice
#

json is string in ram byte stream in disk
how do you loop through a string?
though i think you should create the underlining class in c#

white geyser
#

When is OnDrawGizmos called

slender bridge
# kindred comet How do I loop through a json

You are gonna have to give more context to what you are trying to do with json. In unity, most people convert a json file to c# class using unitys built in Json utility class or newtonsoft.

kindred comet
gaunt ice
#

create the class, dont use the dictionary

kindred comet
#

huh

slender bridge
#

Creating a class will be cleaner and easier to access the key names than a dictionary.

kindred comet
#

I mean sure but how do I do it

slender bridge
#

Do you not know what a class is?

kindred comet
#

I'm new to unity

#

but kinda

#

yeah

#

My json looks like this:

{
    "PeriodicTable": [
        {
            "Atomic Number": "1",
            "Element": "H",
            "Name": "Hydrogen",
            "Group": "1",
            "Atomic Mass": "1.00797",
            "Protons": "1",
            "Neutrons": "0",
            "Electrons": "1",
            "State of Matter": "Gas",
            "Valence Electrons": "1",
            "Period": "1"
        },
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main : MonoBehaviour
{

    public TextAsset jsonData;
    [System.Serializable]
    public class JsonLoader{
        public int AtomicNumber;   
        public string Symbol;
        public string Name;
        public int Group;
        public float AtomicMass;
        public int Protons;
        public int Neutrons;
        public int Electrons;
        public string StateOfMatter;
        public int ValenceElectrons;
        public int Period;
    }
    void Start()
    {
        
    }
}
#

and that's my script

#

idk where to go from here i alr tried everything

gaunt ice
#

json 101
[]=array
{}=object (the class)

kindred comet
#

So like a dictionary?

gaunt ice
#

so you have an array of JsonLoader class, and the field name is peridodictable

kindred comet
#

the issue is idk what JsonLoader is exactly all i know is it has all my variables i need

#

and i don't know how to use that information to convert my json into a usable dictionary / array / whatever

gaunt ice
#

btw you can rename the class to other eg Atom, more easy to read

kindred comet
#

alr

#

where do i go from here tho

gaunt ice
#
[System.Serializable]
public class Chemistry{
  public Atom[] periodictable;
}
```The parser will automatic create the class you passed into generic parameter (ie the name inside <> ) for you
kindred comet
#

well now what

slender bridge
#

And learn

gaunt ice
#

I wonder how you get the json if you dont know json...

timber tide
#

can just treat it as text and make your own parser if you want

swift crag
#

note that you aren't going to be writing and reading json yourself

#

you're just going to tell JsonUtility "please turn this object into JSON" or "please turn this JSON into an object"

lofty lotus
#

what's the best practice for handling when an animation is candled and unable to call the method at the end, ex. an attack get's canceled that needs an end attack method to be called

timber tide
#

interupt the animation and change state

slow crystal
#

Why I can't call the same method in Awake() and Start() ?

gaunt ice
#

what same method?

slow crystal
#

GameController.instance.UpdateLife(health);

verbal dome
gaunt ice
#

i guess NRE

#

the instance is null

verbal dome
#

Maybe it hasnt been initialized in Awake yet

slow crystal
#

I've already fix this error

verbal dome
#

Its good practice to do intialization in Awake, and anything that relies on other classes in Start

slow crystal
verbal dome
slow crystal
#

Makes sense

#

Thank you for help guys!

thorny spruce
#

what method is called when a object is instantiated

thorny spruce
#

thank you, and sorry for not looking at the messages above

woeful hedge
#
IEnumerator Gunfire(int FireNoteIndex)
    {
        Debug.Log("Gun");
        gameObject.GetComponent<SpriteRenderer>().sprite = AttackSprites[0];
        yield return null;
    }```
#

So I just made my IDLE animations speed goes to 0 and run this Coroutine.
I checked the Coroutine Started but the Sprite doesn't change to AttackSprites[0] and remained to animation Sprites.
what should I do to change the sprite?

polar acorn
#

Why is this a coroutine? This has no delays or anything in it

woeful hedge
#

will be

languid spire
#

double check that AttackSprites[0] is indeed a different Sprite

woeful hedge
#

different

#

(paused when the issue comes)

polar acorn
languid spire
#

that is you assuming, not checking the actual code/data

woeful hedge
#

ok?

woeful hedge
rare basin
#

are you sure you are not overriding the sprite anywhere else?

#

because if these logs are true, then it has changed the sprite to wakamo_attack_1_0

#

and if it show that is is not wakamo_attack_1_0 then something else changed it somewhere

woeful hedge
#

the result of that code shows idle_3, and stopped animations

rare basin
#

use a debugger

#

put a breakpoint after changing the sprite

#

and see if it has the correct sprite

#

if yes, then you are overriding it somewhere else

languid spire
#

or we are looking at 2 different game objects

rare basin
#

or this

woeful hedge
rare basin
#

just do what you have been told

woeful hedge
#

wait I need to find how to do in vsc

languid spire
#

debug.log the GetInstanceId() in both cases to make sure they are the same objet

cerulean kestrel
#

im making a vr game and i want that whenever the button is pressed, the door opens. how?

rare basin
#

that's such a generic question

#

you can handle it in many ways

cerulean kestrel
#

i kinda just started lol

rare basin
#

open the door via animation, move it by code, whatever you want

#

make interaction system for the buttons

#

so you can interact with it

#

and link the Interact() of this particular button to open the door

cerulean kestrel
#

i have never coded once in my life

#

THATS the problem

rare basin
#

then how do you expect to get help?

#

when you wont even understand the given help

cerulean kestrel
#

oh

#

huh

eternal falconBOT
#

:teacher: Unity Learn ↗

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

cerulean kestrel
#

ok then geez

summer stump
rare basin
#

good luck on that long journey, dont give up 😄

cerulean kestrel
#

oh damn ok thx

ruby python
#

!code

eternal falconBOT
ruby python
#

Hi all, okay, so I'm trying to hide objects in a hierarchy by firing a ray from the camera (Camera is always a fixed view looking at the player character, so anything in between the two should turn off)

The issue I'm having is turning the objects back on, the way I've got it at the moment, the object that should be 'inactive' is flashing on and off, and I'm not sure how to fix it. Could anyone take a look please and point me in the right direction?

RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, objectToHideLayerMask))
        {
            Debug.Log("Hit Something that should be hidden now");

            GameObject objectHit = hit.transform.gameObject;
            objectToHide = objectHit.transform.parent.gameObject;
            objectToHide.SetActive(false);
        }
        else
        {
            if (objectToHide != null)
            {
                objectToHide.SetActive(true);
                objectToHide = null;
            }
        }
rare basin
#

you cannot detect disabled colliders

#

with raycasts

ruby python
#

Ah crap, of course you can't. 😕

rare basin
#

you might want to for example only disable the renderer

#

but keep the collider on (as trigger so you cant collide with it)

#

so the object won't be visible

ruby python
#

tbh I did think that, but it would be massively inefficiant (the hierarchy is floors of a building with a crapton of items in each floor.

rare basin
#

why would that be inefficiant

#

it doesn't make any difference if you disable the entire object or just the renderer

ruby python
#

Because I would have to disable/enable every single mesh renderer.

rare basin
#

the object is still phyiscally there

rare basin
#

so instead, just disable/enable the renderers

#

objectToHide.GetComponent<MeshRenderer>().enabled = false;

#

assuming the renderer is attached to objectToHide

ruby python
#

Yeah with one 'operation', disabling the renderers for every object would be different.

rare basin
#

no

ruby python
#

There's a renderer for the actual buildings floor. But the floors are populated with lots of other seperate objects (chairs/lamps/furniture etc etc).

#

Each with their own renderer.

rare basin
#

so what is the issue

#

i still dont understand

#

is objectToHide the prop?

ruby python
#

objectToHide is to hide the floor. The furniture objects are children of the floor object.

summer stump
#

When you disable the parent object, it goes through and disables each child already. This would be more efficient since it only deals with one component on each object

swift crag
#

the colliders are lost, though, and that's an issue

#

I would suggest redesigning this a little.

rare basin
#

you should have a Floor class

#

that stores all the props

#

and just disable the props

#

List<Prop> floorProps

#

then just iterate over them and do whatever you need on disable/enable

swift crag
#

Create a collider that encompasses the region. Use that to decide whether or not you want to activate the floor. The collider should not be part of the floor itself.

#

So it'd look like this

#
  • Floor
    • Occlusion Collider <-- raycast against this
    • Contents
#

turn off Contents as needed

#

You could write a little editor script to grow the collider to fit everything on the floor, or just hand-author it

rare basin
#

yea your Floor should be preferably just an empty game object with a Floor class maybe with an additonal UnityEvents OnTurnedOn, OnTurnedOff, list of props etc so you have much more controll, and content/collider sepearte childs

swift crag
#

This assumes you want to disable entire floors at a time.

ruby python
chilly barn
#

I’ve got a small problem, I’m trying to make it so when the player walks into a “pod” the player movement cancels and the camera switches to the pod. Those both work but I made it so you could move the pod after and the player gets left behind.

My plan is to make the player speed a variable I can match to the pod’s when canMove= false, but I can’t figure that out

languid spire
#

why not just parent the player to the pod?

swift crag
#

You shouldn't try to make the player's movement exactly match the vehicle's, yes.

#

that'd be a never-ending treadmill of problems

rare basin
swift crag
#

what if the player gets stuck on something and the vehicle doesn't, or vice-versa?

#

it sounds like you want the player to enter the vehicle and then pilot the vehicle around

ruby python
woeful hedge
rare basin
#

that is not what i told you to do

woeful hedge
#

then how?

#

uhh where is the sprite

#

yup its not

rare basin
#

AFTER

#

not BEFORE

woeful hedge
#

brain issue

#

sorry

#

than I'll make breakpoint at yield

#

ok the code works so the sprite got changed and returned to idle sprite after 1 frame

#

so who changed damn sprite?

#

the animator?

#

I used this first time, so there are no hidden codes that changes sprites
(at least I wrote)

#

so

  • I made Animator speed to 0.0f (to disable IDLE animations, seems no methods to stop the Animator)
  • and Changed to Other Sprite
  • and It changed to IDLE animation Sprite after 1 frame
  • there is no additional my Components written by me except this and there is no code that changes sprite except this line.
#

but why??

#

does anyone knows how to solve this?

swift crag
#

If the animator writes to a property in any of its states, it will constantly write to that property

#

One option is to set the property in LateUpdate

#

Update runs before animators. LateUpdate runs after.

#

Setting the layer weight to zero might work? I do not remember.

#

(but you can't set the weight of the default layer)

woeful hedge
#

will disable animator should work?

#

hmm anyways thanks

swift crag
#

Yes, disabling the animator would stop it from doing anything.

proven lark
#

I just started unity and this is my first time coding and i was wondering what the bracets mean in code

swift crag
#

Braces group multiple statements into a single block statement.

languid spire
# proven lark

they define something called Scope. That is the period of the code that the varaibles defined with in are alive

swift crag
#

A statement is, intuitively, a single line of code.

#

(that is not the technical definition, but good enough for the moment)

proven lark
#

what happens if i leave out the braces?

swift crag
#

A block statement has its own scope, as Steve said. Variables you declare inside of it stop existing once you leave it.

ruby python
#

Basically tells Unity that what is inside them belongs to the 'private void Start()' 'chunk' of code.

woeful hedge
swift crag
proven lark
#

oh okay

#

and what about this

#

why are there braces throughout everything

#

rather than just two defining start and finish

swift crag
#

You aren't allowed to declare a method without a body. You have to use { braces } to define a method body.

#

Hence the error.

polar acorn
ruby python
#

Because if, else if and else are essentially completely seperate from each other.

swift crag
#

if statements do not require this. They just apply to whatever the next statement is.

languid spire
#

because Scope can have many levels, in this case they are defining a Scope for the if statement

swift crag
#

A block statement groups many statements into one big statement.

proven lark
#

oh okay

#

i think i understand it now

swift crag
#

Without braces, you'd only ever be able to put a single statement after an if / else if/ etc.

polar acorn
#

The braces contain all the code inside them and basically turn them into one line. if statements apply only to the next line, if that line is a block, then it applies to everything in the braces

swift crag
#

which would be very limiting

woeful hedge
swift crag
#

they're just not in your screenshot

proven lark
#

yeah i know

swift crag
#

and a pair of braces that start and end the class you declared the method inside of

ruby python
#

If it helps, try to thing that anything inside the { } is 'written' on a post-it note of it's own. It's seperate from everything else, but you can cross reference.

proven lark
#

u guys are really helpful

#

tysm

ruby python
# chilly barn Exactly this yeah

Look at the code I posted, will need a little tweaking as I use an interaction script between the player and the vehicle, but it should point you in the right direction.

chilly barn
#

Learn things along the way

#

Plus then I have a bunch of placeholder code for common stuff I can cannibalize later

ocean blaze
#

guys I'm actually gonna cry ok so my game is a 2d platformer and whenever the player dies it resets the scene (I didn't know how to make respawn points in the middle of development) the problem was that my audio reset so to fix this I made a don't destroy on load script but that also came with some problems for instance if I changed scenes the audio would still play creating more background music and them over lapping if you have any suggestions or things to help ping me pls!!

frosty hound
#

If resetting the scene is just a hack because you didn't want to just reset the level, then why are you trying to fix the audio reset as a result if you know you're going to change the restart functionality later?

eager elm
queen adder
#

hi, my actions.toRun.preformed never happens. does anyone know why that is?

#

here is where MyInput() is called

slender bridge
#

you are only suppose to subscribe to your events once usually in awake or start

queen adder
#

ahhhh

eager elm
queen adder
#

thank you for the input i'll fix it as noted

#

hold

#

OK

#

ANYWAYS, i put the event subscribers in the start function and it still doesnt register the input of ToRun.

#

can anyone tell me why that is

slender bridge
#

and i changed my pic for you

queen adder
#

oh you didnt have to

dusty rivet
#

okay so i have got this class public class GameSettings : MonoBehaviour { public static Difficulty difficulty { get; set; } } and i want to right a script that changed the difficulty and this is what ive got GameObject.FindGameObjectWithTag("Settings").GetComponent<GameSettings>().difficulty = Difficulty.easy;

#

and for the difficulties i have an enum which contains the difficulties

#

but it doesnt seem to be able to change the difficulty in gamesettings

#

is it bc its static

#

if so is there a way i can fix it without making it non static

languid spire
#

yes

slender bridge
#

yes, use a ddol manager or store it in prefs

dusty rivet
#

ohhhh yeah i forgot abt prefs

#

how do i use prefs

#

coz ive forgot

slender bridge
#

PlayerPrefs.

eager elm
dusty rivet
#

alr

dusty rivet
#

also do i need the difficulty varibiable to have the { get; set; }

eager elm
# dusty rivet thank you

And you could also use FindObjectOfType<GameSettings>().someVariable instead of looking for a GO and then looking for the component.

dusty rivet
eager elm
# dusty rivet what does it even do

a property is basically a method that runs when you Set a variable or Get a variable, for example:

public int Health
{
    get { return health; }
    set
    {
        health = value;
        if (health <= 0) PlayerDies();
    }
}
private int health;```
Everytime you call Health -= 1; it checks if the health is below 0 and if it is it called PlayerDies();
dusty rivet
#

why is there two private int health?

dusty rivet
calm coral
languid spire
#

there actually aren't 2 int health's

dusty rivet
#

ohhh yeah ive just realised ones public ones priv

eager elm
languid spire
#

also one has a capital H. case is important

dusty rivet
#

alr thanks guys

normal mango
#

ive got this car to move around by the player and a camera to follow it, but how can i make the camera align when the car turns? attached code is the camera's script

#

thinking that the camera has to have an orbit around the car to always be aligned, but need some help with coding that

normal mango
#

no, its just a script on the main camera

calm coral
normal mango
#

any tutorial i can follow to set it up?

calm coral
kindred comet
#

and don't apply to the current api

short hazel
#

The JsonUtility API hasn't changed in forever, so doubt that

#

Are you using JsonUtility or something else?

calm coral
#

If I recall correclty JsonUtility has some limitations and doesn't fully export complex objects pepeThink it's good for small things though

burnt vapor
#

Some? More like a ton

short hazel
#

Yeah it's pretty limited, but for what they're trying to do it's sufficient

burnt vapor
#

It doesn't even have to be complex objects. Try serializing an array

#

Don't use JsonUtility, use Newtonsoft/JSON.NET

kindred comet
#

som like json 3.0 to json 4.0 or sum shit

spiral oak
#

Is there any way to access the UpdateString of this component?

timber tide
#

what is this component

spiral oak
timber tide
#

oh language stuff

spiral oak
#

yeah

somber tiger
#

I am trying to invoke a ManaRegeneration() method in the update function in an interval of manaRegenCooldown.
Expected Behaviour:
It increases the entityMana value every manaRegenCooldown seconds

Actual behaviour:
it waits manaRegenCooldown seconds and then increases the value every frame.

Here is the code:

[Header("Mana Stats")]
public float entityMana; 
public float maxMana;
public float manaRegenCooldown;
 
void Update()
{
  Invoke("ManaRegeneration", manaRegenCooldown);
}
void ManaRegeneration()
{
  if (entityMana < maxMana)
    entityMana += 10;
        
    if (entityMana > maxMana)
    entityMana = maxMana;
}```
short hazel
safe socket
#

can i ask people to identify what is wrong with my code in this chat

wintry quarry
#

As long as you share it according to !code

eternal falconBOT
safe socket
#

what is a backquote

summer stump
safe socket
#

i found it im jsut chaning something quickly

#
        horizontalInput = Input.GetAxis("Horizontal"); //leftright
        playerRB.velocity = new Vector3(playerRB.velocity.x, 0.0f, playerRB.velocity.z);
        transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed); //moves player
        verticalInput = Input.GetAxis("Vertical");//updown
        if (Input.GetAxis("Vertical") != 0.0f)
        {
            playerRB.velocity = new Vector3(playerRB.velocity.x, 0.0f, playerRB.velocity.z);
        } else
        {
            if (Input.GetAxis("Vertical") == 0.0f)
            {
                playerRB.AddForce(Vector3.up * (0 - 5), ForceMode.Impulse);
            }
            
        }
        transform.Translate(Vector3.up * verticalInput * Time.deltaTime * speed); //moves player
    }
}

Basically, I want to have a downard force constantly applying to an object which the player can move up,down,left,right (including up and left at same time and stuff like that), but I dont know how to change gravity on rigidbody without chaning mass (I do not want to change mass if possible). Solution was to not use gravity and instead use a constant downward impulse force that only applies if player is not moving upwards (i might change this so it will still apply but less force if player moves upwards). However if i click vertical force once the downard force stops applying (this is my issue). What is wrong in my code for the downard force to only work at start

#

this is in void update

wintry quarry
safe socket
#

I was chanign something else it wasnt mass sorry let me check again

wintry quarry
#

You also seem to be mixing Rigidbody motion with transform.Translate, which is a recipe for failure

#

Not only that but you're assigning y velocity to 0 every frame and then also trying to do jumping with forces

#

All in all it's kind of a mess at the moment

#

You're essentially mixing 3 different movement strategies in a way where they'll all clash with each other

timber tide
somber tiger
#

I tried it with coroutines as well, same result

#

does it have to do with calling it in Update?

safe socket
#

What is an alternative

pliant mist
#

I want to make something move around the radius of a circle based on mouse input i.e right mouse move right left mouse move left how do I do this? I’m sssuming some type of sin cos

safe socket
#

Im going to turn gravity off and stop the new assignment to velocty in every frame

summer stump
safe socket
#

why is rigidbody movement better than transform

summer stump
timber tide
somber tiger
#

So using a coroutine in Start() means that it will run all the time?

timber tide
#

yep, you do a while loop in the coroutine and it'll wake up every so often, do its job, then sleep

#

but make sure you're yielding correctly else you'll freeze unity

safe socket
rocky canyon
#

u could always manipulate its velocity

summer stump
safe socket
#

ok thank you

dusty rivet
#

does anyone know what this error means? ArgumentNullException: Value cannot be null. Parameter name: _unity_self UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <347e3e2bef8c4deb82c9790c6e198135>:0) UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <27a779fc555e412cad6318e4bfb44443>:0) UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <27a779fc555e412cad6318e4bfb44443>:0) UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <27a779fc555e412cad6318e4bfb44443>:0) UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <27a779fc555e412cad6318e4bfb44443>:0) UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEngine.UIElements.Panel.UpdateBindings () (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEditor.RetainedMode.UpdateSchedulers () (at <27a779fc555e412cad6318e4bfb44443>:0) i know it says ArgumentNullException and i know that that means theres a null value that cant be null but i dont know what value it it and when i double click on the error nothing happens

rocky canyon
#

it appears to be an editor bug/error

#

restart will prob clear it

dusty rivet
#

alr

rocky canyon
#

UnityEditor.UIElements usually gives it away

dusty rivet
#

yep thats fixed it now thanks

rocky canyon
#

sometimes resetting the layout will also fix it.. but nothing beats a good ole restart

proper bobcat
molten horizon
#

Hi! I cannot for the life of me figure out how to remove a component from a gameobject. The component is an interface script IAbility. Any ideas? This is the script I've tried but isn't working> void RemoveAbilityScript(IAbility ability) { if (!CanRemoveScripts) { return; } if (ability == null) { return; } string abilityName = ability.ToString(); var componentToRemove = GetComponent(abilityName); Destroy(componentToRemove); }

quasi plover
short hazel
molten horizon
short hazel
#

Okay so you need to remove one of the concrete components that implements the interface

#

You can make a generic method for this, with a type constraint

molten horizon
#

Maybe I could do GetComponents<IAbility>() and choose the one in that list because I know which one i need?

#

Nevermind that wouldn't work because I can't control the order

short hazel
#

void RemoveAbility<T>() where T : IAbility

#

Then GetComponent<T>() in it, and destroy that

molten horizon
#

Ok let my try that

short hazel
#

After that, you can call the method and pass the component type to remove, and with the type constraint, it'll produce a compiler error if you pass a type that does not implement the interface

molten horizon
#

the GetComponent<T>() calls an error "Cannot convert T to UnityEngine.object

short hazel
#

Show your updated code

molten horizon
#
    {
        Destroy(GetComponent<T>());
    }
``` And here is where I assign the variable to be removed: ```

public void AssignAbility(IAbility newAbility, int abilityNum, Ability abilityForList)
    {
        abilities[abilityNum] = abilityForList;

        switch (abilityNum) 
        {
            case 0:
                RemoveAbility<ability1>();
                ability1 = newAbility;
                break;
            case 1:
                RemoveAbility<ability2>();
                ability2 = newAbility;
                break;
            case 2:
                RemoveAbility<ability3>();
                ability3 = newAbility;
                break;
        }
    }```
#

But that also calls an error because ability1 cannot be found

short hazel
#

Yeah generic types don't work like that, you cannot treat the things you pass in the <> as variables

#

So you cannot use generic types in this context

molten horizon
#

Ok, so what would I do? I've tried Type.GetType(ability1.ToString()); But it returns null so it doesn't work

short hazel
#

Revert to the old code, get all the components that implements that interface, loop through them, and do an equality check

#

Weird thing for abilities to be attached to game object though, usually they're simple classes stored in a list

eager elm
timber tide
#

usually you use generics to avoid these types of switch statements

#

I wouldn't suggest doing them if you're not well verse in them and just stick to comparisons for now

molten horizon
eager elm
#

and then using that as a parameter

molten horizon
eager elm
#

or, you add a method called DestroyMe() in your interface that you can then call.

molten horizon
rocky canyon
eager elm
molten horizon
#

I'll try to convert the current system

#

Thank you for the help

stuck palm
#

whats the data type for a 3d object? like if i want to change a gameobjects 3d object

amber spruce
#

how would i do attacks i have a animation for it and have it set up to attack when you press left click but how do i have it do stuff to enemies when you attack them like how do i calculate that you are hitting them

stuck palm
#

like mesh i guess

#

like if i want a gameobject to have a different look

slender nymph
slender nymph
amber spruce
#

if i try to settrigger a trigger that isnt there will there be a error

slender nymph
#

yes

#

assuming you are referring to animator parameters

amber spruce
#

yeah

#

is there a way to check if thats a parameter first?

slender nymph
#

correction, you get a warning not an error

#

as for whether there's a method to check if a parameter exists, i don't know off hand but you can check the !docs

eternal falconBOT
amber spruce
#

any idea why im getting this

NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List1[T] inEdges, System.Collections.Generic.List1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <f94752164e14499c83c250d9839d9e96>:0)

slender nymph
#

editor error, likely due to having the animator open. you can ignore it

amber spruce
#

ah ok i thought it was smth with my code lol

summer stump
amber spruce
#

ah ok

#

why is this not working i get the hit1 but not hit2

  Collider[] hitEnemies = Physics.OverlapSphere(transform.position, 2f, enemyLayer);
  Debug.Log("Hit1");
  foreach (Collider enemy in hitEnemies)
  {
     
      /*EnemyHealth enemyHealth = enemy.GetComponent<EnemyHealth>();

      if (enemyHealth != null)
      {
          enemyHealth.TakeDamage(punchForce);
      }*/
      Debug.Log("Hit2");
      enemy.GetComponent<Animator>().SetTrigger("Hurt");
  }
#

im hitting a enemy

slender nymph
#

apparently not

#

note that just because Hit1 prints, does not mean you are actually hitting anything

amber spruce
#

figured it out

#

i was trying to do it for 3d when my game is 2d

queen adder
#

I created a base class for an item and insert that before the default time in Script Execution Order. Will that execution order affect the inherited classes?


[DefaultExecutionOrder(-10000)]
public class ItemBase : ScriptableObject
{ }

// Will it affect?
public class ItemInherited : ItemBase
{ }

// Both shown in the list inside Script Execution Order
slender nymph
#

it should, yes

#

also the attribute does not add them to the list in the script execution order settings

sour arch
#

good evening all,
I've been throwing my head at the wall of 3d for a long time but looking to make the switch from 3d to 2d, I'm trying to avoid entering tutorial hell (again), any good written documents (not including the unity docs as im not sure how they piece together) about movement etc

rich adder
sour arch
#

I will admit i had a google but it just threw a mishmash of yt tutorials and uh, yeah i've watched too many lol

rich adder
#

the engine is 3D anyway

#

youll always working in 3d technically

unreal imp
#

guys this piece of code wont lag and executated every frame? I mean if it was executed only one time void Update() { if (Gun.GetComponent<Gun>().ammo <= 0 && !gun.GetBool("OutOfAmmo")) { gun.SetBool("OutOfAmmo", true); shootEmpty.Play(); } }

rich adder
#

GetComponent every frame 😬

ivory bobcat
sour arch
# rich adder the engine is 3D anyway

I know, but i'm hoping to go into it from scratch.
I over scoped for my first few games, published a few but they were abslutely clusters and i followed a lot of tutorials (didn't learn much) So my knowledge is fairly scatter brained across a lot of random things

unreal imp
rich adder
#

negative

#

You're calling it everyframe because that condition gets hit first

unreal imp
#

so how i should solve it?

rich adder
sour arch
#

Void lateupdate could work for that?

sour arch
#

i think

#

yeah what dalphat said lol

rich adder
#

no you simply "Cache it"

#

yea

vernal sequoia
#

Hello. Can someone tell me pls if I can use the IgnoreCollision method to make the ray ignore objects with a specific tag. An example is below.

public class RaycastLearn : MonoBehaviour
{
    public string[] tagsToIgnore = { "Base", "Wall" };
    public GameObject[] objectsToIgnore;
    void Update()
    { 
        Vector3 rayOrigin = transform.position;
        Vector3 rayDirection = transform.forward;

        RaycastHit hit;

        foreach (string tagToIgnore in tagsToIgnore)
        {
            objectsToIgnore = GameObject.FindGameObjectsWithTag(tagToIgnore);
        }
        
        foreach (GameObject objToIgnore in objectsToIgnore)
        {
            Physics.IgnoreCollision(gameObject.GetComponent<Collider>(), objToIgnore.GetComponent<Collider>());
        }
        
        if (Physics.Raycast(rayOrigin, rayDirection, out hit, Mathf.Infinity))
        {
            Debug.Log("Hit object: " + hit.collider.gameObject.name);
        }

        Debug.DrawRay(rayOrigin, rayDirection * 10f, Color.green);
    }
}
sour arch
unreal imp
# rich adder https://discord.com/channels/489222168727519232/497874004401586176/1185718061928...

these codes too? first code: ``` void Update()
{
if (Input.GetKeyUp(KeyCode.E) && !objectAnimator.GetBool("Flushing"))
{
objectAnimator = gameObject.GetComponent<Animator>();
ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
if (Physics.Raycast(ray, out hit, interactDistance) && hit.collider.gameObject == gameObject)
{
InteractWithObject();
}
}
else if (objectAnimator.GetBool("Flushing"))
{
objectAnimator.SetBool("Flushing", false);
}

    if (!toiletExplodes.active)
    {
        audi.Stop();
    }
 }``` second code: ```    void Update()
{
    if (Input.GetMouseButtonDown(0)) {
        Invoke("IsShootingTrigger", 0.1f);
    }
}```
#

It seems that my fears came true xd, every frame is executed this

rich adder
#

uh yeah whats the point of doing this at runtime

#

if the component is already on THIS object

unreal imp
#

welp i was trying to make a flushing animation on a toilet,simply that

dusty rivet
#

is there a way i can change the RectTransform.right value in code by itself

unreal imp