#💻┃code-beginner

1 messages · Page 635 of 1

umbral rock
#

well, i added a velocity, so 1 move function for moving the player and the other for moving him down with gravity

polar acorn
#

You should use one call so grounded is accurate whenever you check it

umbral rock
#

oooh yes i can see, now that i have 1 move function it works

#

how do i apply gravity then? do i add a vector3 in the move function for movement and then on the y axis i add the gravity?

#

aah yes found it guys, thank u all!

acoustic belfry
#

oh, well, thanks :3

formal valley
#

emmm then is there in unity that calculate the distance between two object??

vagrant wolf
#

I downloaded unity and i just noticed my unity is in low quality how can i fix that?

rich adder
#

or the Player Quality

vagrant wolf
rich adder
#

you cropped out the Zoom amount in the GameView

vagrant wolf
#

the player quality and gameview

vagrant wolf
rich adder
vagrant wolf
#

I changed it to 1920 but still seems low quality

#

jUST LOOK AT THIS :((

rich adder
vagrant wolf
rich adder
#

can you like show the Scale number?

cursive hamlet
#

this is what i have


public class RuinStoneScript : MonoBehaviour
{
    public string interactionKey = "e";
    private bool isInteracted = false;
    private Renderer stoneRenderer;
    private MaterialPropertyBlock propertyBlock;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        stoneRenderer = GetComponent<Renderer>();
        propertyBlock = new MaterialPropertyBlock();
    }

    // Update is called once per frame
    void Update()
    {
        if (isInteracted == false && Input.GetKeyDown(interactionKey))
        {
            Interact();
        }
    }

    private void Interact()
    {
        // Ensure the emission color is green when interacted
        Debug.Log("Interacting with " + gameObject.name);

        // Get the current material properties
        stoneRenderer.GetPropertyBlock(propertyBlock);

        // Enable the DECAL EMISSION (assuming this is controlling the emission effect)
        stoneRenderer.material.EnableKeyword("_DECALEMISSIONONOFF");

        // Set the emission color to green
        propertyBlock.SetColor("_DecalEmissionColor", Color.green);

        // Apply the property block changes
        stoneRenderer.SetPropertyBlock(propertyBlock);

        Debug.Log("Emission should now be green for " + gameObject.name);

        isInteracted = true;
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            Debug.Log("Press 'E' to interact with " + gameObject.name);
        }
    }
}```
rich adder
#

I havent mentioned anything about resolutions

vagrant wolf
rich adder
eternal falconBOT
rich adder
#

thats why its blurry looking

vagrant wolf
rich adder
cursive hamlet
rich adder
vagrant wolf
cursive hamlet
#

i think thats his custom shader

rich adder
rich adder
scarlet aspen
#

Is it better start learning programming with “beginner scripting” or “unity learn essentials programming pathways”?

rich adder
#

wouldn't hurt would it

#

the pathways just kinda ease you into the same topics

scarlet aspen
# rich adder both

Which one first? I’m getting mad for the first tutorials of loops, I read comments that says they are not explaining good some things

rich adder
cursive hamlet
rich adder
#

woldnt it be easier to just have 2 Materials ?

#

thats generally what i do, I swap them out so its easy

#

InteractedMaterial as a field / resource to replace it with

scarlet aspen
cursive hamlet
#

im not sure, im new to this and its for my class. I originally had one texture which has the same symbol for the rock, i duplicated it a few times and changed each texture's symbol to something unique and assigned it to the rocks so all rocks have different symbols

rich adder
scarlet aspen
vagrant wolf
#

I deleted something and now it looks like this

#

Idk how to get the texture back

#

I did ctrl+ z

#

no work

wintry quarry
vagrant wolf
#

I got the files from the trash now its back tys

vernal thorn
#

is there a way too move just the sprite of an object? (Whitout the collider)

frosty hound
#

Sprites have no position, it's the object itself that has the transform.

#

Make the sprite a child of your root object and offset its local position instead

#

Generally speaking, you want your "art" to be children of a root object anyway.

vernal thorn
#

oh thanks never did that lmao

rare elm
#

any opinions on text animator vs super text mesh vs alternatives? i'm kind of inclined to like the tag approach in ta but i'm hoping to hear from users

timber tide
#

make your own for free

woeful locust
#

heyo, im working on making a scriptable object where i can make new heroes for my game. however, i want the affinity option to be a dropdown in the engine instead ofa script, how would I go about doing this? I tried making a lis tbut that didn't work

 using UnityEngine;

[CreateAssetMenu(fileName = "NewHero", menuName = "Hero")]
public class Hero : ScriptableObject
{
  public  string Name;
    public int HP;
    public int MP;
    public string affinity;
    public Sprite artwork;

}
timber tide
#

make affinity an enum

woeful locust
#

time to learn what an enum is :/

rare elm
#

enum Season { Spring, Summer, Autumn, Winter };

naive pawn
rare elm
#

it's an association of labels to integer values at the lexer level

#

in that example above, Spring is 0

#

but you don't have to manage it

#

this gives C# a way to say "here are the specific permitted labels"

#

a type is created (in this case Season)

#

you then use that type on the field you're trying to expose in the editor, and the editor now knows what things are permitted too

woeful locust
#
using UnityEngine;

[CreateAssetMenu(fileName = "NewHero", menuName = "Hero")]
public class Hero : ScriptableObject
{
  public  string Name;
    public int HP;
    public int MP;
    public enum affinity{
      Earth,
      Fire,
      Water
    }
    public Sprite artwork;

}
#

this is what i tried(it doesn't work)

naive pawn
#

you have to define and use the enum separately

rare elm
#

the enum goes outside the class

naive pawn
#

go look at an enum guide

woeful locust
#

i see

#

wait

naive pawn
rare elm
#

you're going to end up calling that enum Element or something

#

then where you tried to put it, you write public Element myElementFieldNameGoesHere

#

think about it like it's actually a real type, in the way integers and strings and so on are

#

you're going to want to be able to use it more than once

#

that's not going to be the only place you use elements

#

and you don't want to have to repeat yourself, or make sure they're all the same

#

you'll want the elemental damage bonus on your sword, the elemental defense bonus on your shield, etc, etc

#

those should (presumably) all use the same concept of what an element actually is

woeful locust
#

i seee

rare elm
#

enums, like structs and classes, are a way for you to create your own types

#

this is good for a bunch of reasons, but one of the big ones is when you teach c# how your data actually works, the compiler can start catching your mistakes for you

#

consider the season example i gave, above

#

if someone accidentally wrote "fall" instead of "autumn," the compiler can now catch it

rare elm
#

oh hell, i don't know what c# calls them. whatever the label is of the member method

#

Name, HP, MP, and artwork, above

woeful locust
#

well

#

i just tried this

using UnityEngine;

[CreateAssetMenu(fileName = "NewHero", menuName = "Hero")]
    public enum affinity{
      Earth,
      Fire,
      Water
    }
public class Hero : ScriptableObject
{
  public  string Name;
    public int HP;
    public int MP;

    public affinity Affinity;
    public Sprite artwork;

}
polar dust
woeful locust
#

Assets\Hero.cs(3,2): error CS0592: Attribute 'CreateAssetMenu' is not valid on this declaration type. It is only valid on 'class' declarations.

rare elm
#

that line above the thing you wrote is part of the class

#

you shouldn't be splitting it off that way

woeful locust
rare elm
#

sorry, i'm new to unity and c#, i'm occasionially going to use phrasing from other languages because i'm liquid dumbass concentrate

woeful locust
#

im new to unity and c#

#

i only really know java

#

and im not even a pro at that

#

it worked! thank u :3

rare elm
#

cool

#

so. text animator vs super text mesh. surely someone in here has used them both

frosty hound
#

I've checked out Super Text Mesh, but that was a long time ago. I didn't like it, and I actively use Text Animator now.

rare elm
#

okay. do you happen to remember what you disliked?

frosty hound
#

I don't, this was before TA existed.

rare elm
#

gotcha.

#

but you're generally satisfied with TA?

frosty hound
#

But I do remember appreciating that TA literally sat on top of a TMPRO component.

rare elm
#

is that about being a standard interface and being easy to integrate, or something?

frosty hound
#

You don't have to do anything other than add the text animator to an existing text mesh pro object and you're done.

rare elm
#

i kind of feel like i can just make a tag for each alien species, and i'll get uniformly styled text fairly conveniently. is that sane?

#

like, it's not d&d, but that's a sufficiently universal metaphor, so, goblins would get bold green text, vampires would get dark red text in a halloween bleeding font, ghosts would get 75% alpha text in a sketch font, &c &c &c

frosty hound
#

Yep, you can easily make your own tags like that.

noble cedar
#

can someone explain to me this warning?

#

oh my bad wrong channel ill delete it rn

rare elm
#

@noble cedar - something isn't cleaning up behind itself

wintry quarry
noble cedar
wintry quarry
#

reading the full stack trace would be a good start

rare elm
#

@frosty hound - any chance you also have opinions about Pixel Crushers dialog system?

frosty hound
#

I haven't used it, but I know it's always a recommended solution. It's been used successfully in successful games.

noble cedar
wintry quarry
#

I just mean look at the full error message

wintry quarry
#

yeah see all that, that';s a stack trace

#

it's a trace of the program execution stack

#

basically just - which function is currently calling which function, etc...

#

anyway looks like it's netcode related

noble cedar
noble cedar
wintry quarry
#

I didn't say that

#

just that the issue is somehow netcode related

#

it's not necessarily an error in your code

#

it could be a bug in the netcode library itself

naive pawn
#

oh i wasn't scrolled down sorry

timber tide
#

Man, text animator looks like something you can make in one sitting. Maybe I'll make some trashy version and put it up on git

noble cedar
rare elm
#

multiplayer is a classically challenging problem

timber tide
#

do people really pay for someone to throw on some sin waves on text mesh pro and add a parser to it all

rare elm
#

it's probably not well suited for your first game

wintry quarry
rare elm
#

@timber tide - yes, I will pay $65 to save myself three hours.

noble cedar
rare elm
#

that's not far off CA minimum wage

timber tide
#

Yeah true. Maybe I'll make a budget version then lmao

wintry quarry
noble cedar
rare elm
#

@noble cedar - are you using a library or doing it from scratch or what

noble cedar
rare elm
#

like are you setting up some library you found in unity store

#

something like coherence or normcore or nakama or whatever

#

or are you actually opening sockets up

noble cedar
#

I downloaded from there netcode for game objects

rare elm
#

ya your teacher's just wrong. that stuff isn't easy

#

you can do it though

noble cedar
rare elm
#

yeah it's generally one of the most difficult things to do in gaming except in turn based stuff

#

like, it's not too bad for like chess and whatever

#

but for regular games, it's a hard problem. the network isn't instant and coping with that is strange.

#

if you knew how much dark magic netcode was burying for you, etc, etc

noble cedar
rare elm
#

it's a common metaphor

timber tide
#

Unity's solution is pretty simple. You can just do server authoritive approach and funnel everything into the server, and only client-side the camera. Otherwise all the synchronization is pretty straight forward to set up

rare elm
#

anyway, look, there's one other way to look at this: you've managed to put 300h into a project and stuck to it

#

that's the actual thing that makes a programmer

#

fortitude

#

so you're doing something right

noble cedar
#

is there way to check total time in one project?

#

I am just estimating the time

rare elm
#

that's 28-ish fulltime days

#

or 150-ish 2 hour days

noble cedar
rare elm
#

if you've done five days a week for a little under four hours a day, you're there.

noble cedar
#

so again is there way to check total time spent in project?

rare elm
#

i don't believe unity times you.

noble cedar
echo kite
#

how do i make weapon recoil it keeps glitching out

naive pawn
#

gonna need a lot more detail than that

echo kite
#

now i separated it from gun script

#

and it goes left and up

#

and rotates around

#

if u put intensity to high

#

if not this is what u get

#

and now it doesnt even work

echo kite
# naive pawn gonna need a lot more detail than that
using UnityEngine;

public class ProceduralRecoil : MonoBehaviour
{
    public Transform cameraTransform;
    public float recoilX = -3f; // Vertical recoil
    public float recoilY = 2f; // Horizontal recoil
    public float recoilZ = -1f; // Pushback effect
    public float snappiness = 15f; // How fast the recoil applies
    public float returnSpeed = 6f; // How fast it returns to normal

    private Quaternion originalRotation;
    private Vector3 originalPosition;
    private Vector3 targetPosition;
    private Quaternion targetRotation;

    void Start()
    {
        originalRotation = cameraTransform.localRotation;
        originalPosition = cameraTransform.localPosition;
        targetRotation = originalRotation;
        targetPosition = originalPosition;
    }

    void Update()
    {
        // Smoothly transition to recoil rotation and position
        cameraTransform.localRotation = Quaternion.Slerp(cameraTransform.localRotation, targetRotation, Time.deltaTime * snappiness);
        cameraTransform.localPosition = Vector3.Lerp(cameraTransform.localPosition, targetPosition, Time.deltaTime * snappiness);
        
        // Gradually return to original rotation and position
        targetRotation = Quaternion.Slerp(targetRotation, originalRotation, Time.deltaTime * returnSpeed);
        targetPosition = Vector3.Lerp(targetPosition, originalPosition, Time.deltaTime * returnSpeed);
    }

    public void Recoil()
    {
        float recoilUp = Random.Range(recoilX * 0.8f, recoilX * 1.2f);
        float recoilSide = Random.Range(-recoilY, recoilY);
        targetRotation *= Quaternion.Euler(recoilUp, recoilSide, 0);
        targetPosition += new Vector3(0, 0, recoilZ); // Push camera slightly backward
    }
}
``` this is last script
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProceduralRecoil : MonoBehaviour
{
    Vector3 currentRotation, targetRotation, initialGunPosition;
    Quaternion baseGunRotation;
    public Transform cam; // Camera reference

    [SerializeField] float recoilX = 1.5f;
    [SerializeField] float recoilY = 1f;
    [SerializeField] float recoilZ = 0.5f;
    [SerializeField] float kickBackZ = 0.05f;

    public float snappiness = 10f;
    public float returnAmount = 15f;

    private bool isRecoiling = false;

    void Start()
    {
        initialGunPosition = transform.localPosition;
        baseGunRotation = Quaternion.Euler(0, 90, 0); // Base rotation of the gun
    }

    void Update()
    {
        if (isRecoiling)
        {
            // Reset gun rotation
            targetRotation = Vector3.Lerp(targetRotation, Vector3.zero, Time.deltaTime * returnAmount);
            currentRotation = Vector3.Slerp(currentRotation, targetRotation, Time.fixedDeltaTime * snappiness);
            transform.localRotation = baseGunRotation * Quaternion.Euler(currentRotation);

            Back();
        }
    }

    public void Recoil()
    {
        // Apply recoil effects
        targetRotation += new Vector3(
            -Mathf.Clamp(recoilX, 0, 2), 
            Random.Range(-recoilY, recoilY), 
            Random.Range(-recoilZ, recoilZ)
        );

        // Apply backward kick
        isRecoiling = true;
    }

    void Back()
    {
        // Smoothly return the gun to its original position
        if (Vector3.Distance(transform.localPosition, initialGunPosition) > 0.01f)
        {
            transform.localPosition = Vector3.Lerp(transform.localPosition, initialGunPosition, Time.deltaTime * returnAmount);
        }
        else
        {
            isRecoiling = false;
        }
    }
}
rich adder
rich adder
#

an entire class usually is

eternal needle
#

usually the inline code is more for like a couple lines

echo kite
#

whatever

#

i just need help

#

for realistic recoil

rich adder
#

then you should consider making things easier for others to read?

polar acorn
echo kite
#

2 version

rich adder
#

with the same name?

echo kite
rich adder
#

okay.. even more reason to use links, esp one that allows multiple tabs each script

echo kite
#

it does weird twisting

rich adder
#

whats twisting ?

#

videos would help better visualize the problem

#

generally you dont want to AddRecoil to the same object as the Camera.. Since usually 1 script is rotating the camera you will have fighting over the rotation/transform

#

usually a parent container is used

echo kite
#

unlike csgo cod and other games its very unrealistic

echo kite
#

not in this case

#

because camera doesnt move

#

when i shoot

rich adder
verbal dome
echo kite
echo kite
rich adder
verbal dome
echo kite
verbal dome
#

Yeah, thats the answer I was fishing for

echo kite
slender nymph
#

if that were the case then you wouldn't be here trying to get help with it

verbal dome
#

We are tired of people coming in here with low effort AI crap

#

And not even disclosing that AI was used

echo kite
echo kite
verbal dome
#

The internet is riddled with FPS recoil tutorials

echo kite
#

And I didn't know that rule either

echo kite
slender nymph
echo kite
#

I did w3schools tutorial

slender nymph
echo kite
#

I didn't find good tutorial

#

All I know is how to make basic thing like csgo 1

#

But not like cod

slender nymph
# echo kite I didn't find good tutorial

no, you didn't find a tutorial that did every little thing for you. you found plenty of tutorials that teach the general concepts you need to know, you just won't use them and put that knowledge together.

echo kite
#

But I don't know how it's supposed to work

slender nymph
# echo kite I did that

no you didn't, you used a bullshit generator to generate bullshit for you instead of learning the concepts

slender nymph
#

then use that knowledge and make your own attempt at implementing recoil and maybe you'll get more help

echo kite
#

But it doesn't come out realistic

#

It comes out what I put

#

Instead of random

#

Recoil

zinc charm
#

I am new to unity, trying to use a region as material sprite from texture2d but my texture comes out weird, I even set the right UV offsets etc.

slender nymph
#

this is a code channel

zinc charm
slender nymph
slender nymph
#

that is a link to a specific message

zinc charm
#

I see

rich adder
edgy radish
#

Thanks, I managed to do it. The problem was that the authentication method used by this old version of MySQL Connector was different, and then utf8mb4 was not supported. I changed the authentication method in MySQL, and set it to utf8.

Thank you very much.

lean cipher
#

Hi so im trying to remake pong and the ball bounces on the bounds but when It makes contact with one of the players (the paddle things) its just phases right through them. Why is that?

eternal needle
eternal needle
#

well guess i shouldve been specific, !code on how to share code

eternal falconBOT
eternal needle
rich adder
#

its also possible your paddle went to Sleep

#

I would keep Sleeping mode to Never Sleep

#

(on the rigidbody2d)

vagrant wolf
#

??? why and the player is assigned

rich adder
#

if its assigned for a fact (eg you checked the inspector and its fine at runtime)
consider checking if there are multiple of same Scripts, with one of the fields not assigned

vagrant wolf
#

Thanks I fixed it

vagrant wolf
#

It wasn't going through earlier why now?

rich adder
vagrant wolf
#

how so

rich adder
vagrant wolf
#

ty

#

is there a way to make the collider match the size?

rich adder
vagrant wolf
#

like always and automatic

rich adder
#

only if they are on the same object

vagrant wolf
rich adder
#

works fine look

#

assuming they have parent whos scale stays at 1,1,1

#

otherwise it won't be exact and you have to take parent scale into account

vagrant wolf
#

Ty. one more thing how do i wait in c++ for a certain time

rich adder
#

default Unit is 1m

rich adder
vagrant wolf
#

I thought it was c++ lol

rich adder
#

nah the Engine itself is written in c++

#

we interact with the API thats in c#

#

make a delay using Update w/Time.delta or Time.time, or Coroutine

vagrant wolf
#

alr i will look into it thank you

#

Have you ever used roblox studio?

rich adder
#

not really

#

i grew up on gmod

vagrant wolf
#

I used it, its pretty easy unlike c# I guess it was meant for kids

rich adder
#

I used LUA to make gmod assets / mods. It was not fun

#

c# is easy

vagrant wolf
#

Luau

rich adder
#

just takes a bit of time getting used it, you'll be wondering why you ever touch something like lua

vagrant wolf
#

Luau and lua the same?

rich adder
#

Luau is a flavor of lua , heavily modified

vagrant wolf
#

roblox studio is like Unity but bad at the same time good

#

roblox studio doesn't have the graphic unity has

#

Can you make values and save them data stores?

#

Nvm almost everything is possible so prob yea

wintry quarry
#

everything is possible

rich adder
#

default answer to "is it possible xyz"

solid heart
#

Hey Im following a tutorial, but I dont understand one thing if he enters the scene and switch to his lvl scene the player appears out of now where how? when I do this my player dont appear

#

In this video we begin by building a small play test arena. After, we add Unity's Input system to our project. We then learn how to set up inputs using our newly created input functionality. We end by creating some player classes which will be used to begin controlling our player character.

► GET MY GAME ON STEAM
https://store.steampowered.co...

▶ Play video
#

min 17:40 the player cloned but I dont undertand how can maybe someone explain please?

timber tide
#

What is player in the first scene and are you tagging it as dont destroy on load

#

Or better question, how are you making a player in the next scene

solid heart
timber tide
#

Then add the player prefab to the next scene?

vagrant wolf
#

How come I'm not finding the rendering mode on material i wanna make it transparent

ember tangle
#

I'm noticing that 2d collider stuff stops working when I use a perspective camera on an angle instead of top down. Is there a workaround for this?

teal viper
rich adder
solid heart
rocky canyon
vagrant wolf
rich adder
#

shiiiiet

vagrant wolf
#

lol

rich adder
#

Anyway it didnt tell you , switch the Surface type to Transparent instead of Opaque

teal viper
#

To be fair, the ai is not wrong. It just doesn't tell the whole story.
The issue is that people relying on it too much, stop thinking with their own head.

rich adder
#

yeah thats what sucks, it just either completely wrong or incomplete
(big problem when you dont know the answer given to you is such a thing)

vagrant wolf
teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

rich adder
#

also confirm the correct answers usually from the unity answers site / stackoverflow

teal viper
timber tide
ember tangle
#

imo if you have no foundation for coding you shouldn't use AI at all or you'll cripple yourself.

vagrant wolf
rich adder
#

main problem comes with over reliance too and especially taken at face value without doubts

vagrant wolf
#

Does unity have tweening?

timber tide
#

coroutines, or just lerp inside of update

vagrant wolf
#

Like tweening animations

#

Quad, linear?

timber tide
#

the animator tweens I guess too yeah

vagrant wolf
#

no way thats cool so i can animate parts

timber tide
#

otherwise there's a bunch of plugins out there

vagrant wolf
#

Interesting

timber tide
# solid heart Thank you so much

Another idea is just destroy the first scene camera such that you make it again in the next scene. That would require removing the DontDestroyOnLoad tag from the first scene camera.

keen owl
#

They are pretty cool and can be used for a lot of things

vagrant wolf
#

cool can't wait to try them out!

woeful locust
timber tide
#

time to learn dictionaries

woeful locust
#

uh oh

#

(thanks)

timber tide
#

basically allows you to make some value type (and references!) point to another

#

and quickly to access

woeful locust
#

i found a youtube video explaining

#

thank you for pointing me in th eright direction

#

🙂

#

so i could do

#
Dictionary<affinity, reaction> affinityRelations = new();```
#

or something of the sort

timber tide
#

Dictionary<affinity, affinity>
If you want to use the same enum

wintry quarry
#

possibly Dictionary<type, float> would be best. You could use 1 for normal, 2 for weak, .5 for resist, or even use other values as needed

woeful locust
#

ou

#

that does make sense

woeful locust
timber tide
#

Like can do
Key = Fire, Value (what is weak against) = Water

wintry quarry
#

Also a possibility^ and then you would have 1 dictionary for weaknesses and 1 for resistances

wintry quarry
#

(assuming they're asymmetrical like Pokemon)

#

there are many ways you could do this, depending on your needs.

woeful locust
#

something along these lines

wintry quarry
#

No idea what I'm looking at here lmao

woeful locust
#

if youa ttack with ffire onto this monster, it repels

#

but im not adding repels, just hte best example i could think of (persona 5)

timber tide
#

If it has multiple weaknesses then you do something like
Dictionary<Affinity, List<Affinity>>

wintry quarry
#

in this case you could do something like:
HashSet<Affinity> resistances and HashSet<Affinity> weakneses if it's tied to a particular monster not a particular type

woeful locust
#

i didn't know how toe xplain

#

its by monster not type

#

thank you

#

(what is HashSet)

wintry quarry
#

what's rpl vs str?

timber tide
#

hashset is dictionary lite

wintry quarry
#

HashSet is a data type that is optimized for Contains, Add, and Remove checks

#

and cannot have duplicates

woeful locust
#

i see

wintry quarry
#

it's faster than List for those operations

woeful locust
timber tide
#

Yeah, if you don't care about ordering of elements. Always go for hashset

#

which most people don't realize how good of a data struct it is with c#

woeful locust
#

order doesnt matter for me tbh

#

so i will do HashSet

wintry quarry
#

main issue with it is it's not serializable in Unity

#

so it's something you have to build at runtime

woeful locust
#

oh.

#

erm

wintry quarry
#

(possibly from a serializable list or array)

woeful locust
#

im not sure if thats aproblem

timber tide
#

oh yeah that's true

#

but in this case if you do want to use dictionaries, you'd probably be just hardcoding the values

#

otherwise need to make a struct middle man to serialize in the editor -> then create dictionary at runtime

woeful locust
#

i see

#

alright

timber tide
#

Weakness types and stuff like this isn't likely to change anyway

woeful locust
#

wait

#

how do i alter for ever object...

vagrant wolf
#

No GameManger??

fast relic
wintry quarry
vagrant wolf
#

Oh, how do i make one

wintry quarry
#

you write it

#

like any other script

sleek geyser
#

hey, i've already asked this question in VR, but i figured it might be better here for visibiity.

im trying to make a multiplayer passthrough XR app. I'm like 90% done with a template, but im facing an issue where my 'Building Block] Networked Avatar is spawning, but isn't following the xr rig. Has anyone had this issue?

fast relic
wintry quarry
#

If you're following a tutorial you'll need to follow the part where they make the GameManager script.

vagrant wolf
#

Thanks I thought it was built in

vagrant wolf
wintry quarry
#

or maybe they will get to it later

vagrant wolf
#

He has almost 2m subscribers lol

wintry quarry
#

that doesn't mean shit lol

#

youtubers are entertainers

#

most youtube tutorials are bad, including the popular ones

#

maybe especially the popular ones

vagrant wolf
#

Watching this guy named Brackeys

wintry quarry
#

yeah brackeys is well known

#

which tutorial

vagrant wolf
#

if I didn't had experience using roblox studio then I don't think I would have lasted the first 2 tutorials

rich adder
#

Jumping from yt to yt won't work well

#

!learn 👇

eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar dust
#

nav isn't a fan of brackets

#

A single tear

rich adder
polar dust
#

I feel like I've got something out of his stuff from way back when

#

So much YouTube content feels like it's useful to beginners but secretly isn't

rich adder
#

He's a good presenter and for specific things it's helpful but his code usually is all over the place

#

Much eaiser when you can recognize where its kinda bad and improve upon it

polar dust
#

I see a fair few people make the mistake of thinking sebastian lagues videos are tutorials, then get very frustrated when they can't get his source code to do what they want

polar dust
rich adder
#

Yup that's the problem , believe me I was there lol

sleek geyser
#

hey has anyone here had experience making things for meta xr headsets?

polar dust
#

Also YouTube is an entertainment game, for a unity tutorial series to actually provide highly useful and informative content, it'll be the most boring thing for beginners

#

The best tutorials I've ever seen are various Unity ones, as those do one thing I've barely seen anyone do. Actually explain why it is they do certain things

rich adder
#

If something is wrong or confusing I delete it

polar dust
#

In one he renamed something and then explained that name was totally arbitrary with no impact on the code.

I don't think I've ever seen anyone do that

#

Also he made gradual changes to the code and stopped halfway through to summarise, before moving on

rich adder
#

Like mass rename all places w that variable ?

#

And yeah variables names are irrelevant they're just for you

polar dust
#

I think it was just a new name he gave to something and the name could have seemed important

rich adder
#

It all gets made into machine code

polar dust
#

I'll try and find the video

spice ember
#

Hi, I'm new to Unity. What is the correct set up for two parts of a player to rotate independently, but use the same physics-based movement? I could give them an empty parent with a Rigidbody for physics based movement, but if it gets rotated then it will affect both children. So do I use a Rb for the child objects? But then, they won't have the same position... shits confusing.

wintry quarry
#

what's the gameplay thing you're trying to accomplish

spice ember
#

I just mean have entirely different code that controls the rotation of each part

spice ember
#

One is movement based, one is mouse based

wintry quarry
#

It just sounds like you would have a RIgidbody parent and then rotate these children via code

spice ember
#

Using transform?

wintry quarry
#

sure

#

is there any reason they need more than that?

#

are they.. gun turrets?

#

Or what

spice ember
#

Yeah tank hull + turret

polar dust
#

lost to time 😔

wintry quarry
#

the tank hull doesn't need anything special, it's just the RB or a child.

The turret you'd just rotate via its Transform.

elfin locust
#

Anybody know why this isnt working. Im new and trying to learn how to script so forgive me if the answer is obvious. Im trying to use this player movement script to be able preserve momentum and allow adjusting midair for platforming. However whenever i test in game i only move along the y axis when jumping.

eternal falconBOT
rich adder
elfin locust
#

didnt realize as im on pc ill fix rq

polar dust
#

I honestly could rant for hours with how much is wrong with the state of online gamedev "tutorials" notlikethis

My book will be called "the illusion of learning"

spice ember
wintry quarry
#

that's the default behavior

#

will the turret's transform be affected by the RB rotation?
Yes but since we're going to update it manually via script in Update it doesn't matter

#

we will overwrite that

wintry quarry
elfin locust
#

yes If i jump and try to move or am already moving, my character will not have any horizontal momentum, only vertical

wintry quarry
#

can you try commenting that part out entirely for a moment

#

I don't think that code is correct - it doesn't really account for the character's rotation properly

spice ember
#

Is setting transform.rotation = in Update() wrong?

wintry quarry
#

if you were not instantly setting the rotation to exactly aim at the mouse, then yes there will be some visible effect from the rotation of the tank body

#

i.e. if you were doing some kind of interpolation or movement over time

wintry quarry
spice ember
#

Not briefly

#

Since the transform of the turret is modified very quickly in update, I wasn't sure how this was happening

wintry quarry
#

you'd have to show it

elfin locust
spice ember
wintry quarry
#

and probably set airControlFactor a lot higher than 0.05

spice ember
# wintry quarry That really depends on your code

Oh I found the cause but am not certain of why it happens. With the hull and turret as children of the empty object with position and rotation set, it works fine. The turret's rotation overrides the Rb rotation perfectly. However, if I set the turret as a parent of the hull (which is still a parent of the empty object) moving offsets the turret's rotation.

I was thinking it's a physics issue, but the hull object in this case literally has nothing attached apart from a mesh renderer so I don't understand why this happens.

wintry quarry
#

that seems backwards

spice ember
#

oops

#

I meant child

wintry quarry
#

idk, again I'd have to see the exact code and setup involved

#

¯_(ツ)_/¯

spice ember
#

idk, this isn't code related

#

the mesh object is interfering somehow

wintry quarry
#

I don't know if I'm convinced.

spice ember
#

The hull has no scripts running. It inherits everything from the empty parent. When they are both children of the empty one with all the movement logic, I have no issues. Same code, but just changing the hierarchy to empty > hull > turret causes this issue.

wintry quarry
#

If you switch to LateUpdate I wonder if it changes anything? It might be some niche update order issue.

#

(for the turret rotation code)

spice ember
#

No difference with that

#

Very weird. I mean I guess there's no difference if I have them both as children, it's just odd not knowing why this is happening.

coral ivy
#

It's been a while since I did animation stuff.. I want to edit some animations but now it seems I can't edit any animations that I have..

I want to add a property but it's locked up.

wintry quarry
#

you have to duplicate it and modify the duplicate

coral ivy
#

Ok I copy pasted it but still can't add property

wintry quarry
#

this isn't a code issue

coral ivy
#

oh right

faint agate
#

bug: Hello, heres a script a I have on the parent of a weapon gameobject. It makes the weapon sway but the problem is that its super choppy. Sometimes when I click play its smooth and other times Its laggy or choppy. Any ideas?
https://pastecode.io/s/ewhto8w9

coral ivy
#

How can I set a 2D collider to only apply collision with non-transparent pixel?

tough trench
#

anyone have a good tutorial that shows how to use scriptable objects

wintry quarry
#

only other colliders

coral ivy
#

I tried adding custom physics shapes:

#

chat gpt is telling me to use polygone collider but it didnt work

wintry quarry
#

those are only important for tilemap colliders

wintry quarry
coral ivy
#

so I added polygone collider to my tilewalls (the tile shown on the picture above) and I tested it, I am not colliding with them.

elfin locust
# elfin locust https://paste.ofcode.org/C8AXPpNHgzrgMWGSqWwQhP

So now im having the issue where when im crouched by the edge of a platform and uncrouch, I get kicked off of it. Im assuming that its because since when i crouch my entire player object including the collider and capsule get transformed down, that my colliders clip the floor and it kicks me off. To fix this would I have to dynamically change my colliders on crouch?

wintry quarry
coral ivy
#

yes I am

wintry quarry
#

then no you wouldn't use anything except the TilemapCollider

wintry quarry
#

just looks like a plan square

coral ivy
#

I am using auto-tile rules and applying custom physics shape to them

wintry quarry
#

Ok and... Do you have a tilemap Collider on your tilemap?

coral ivy
#

yes when I use tilemap collider, its not respecting the physics shape as collider.

wintry quarry
#

what is it doing instead

#

show the collider gizmo

slim salmon
#

Anyone know why isGrounded is logging true & false at the same time when grounded?

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private CharacterController controller;
    private Animator animator;
    private Vector3 velocity;
    private bool grounded;
    public float speed = 5f;
    public float jumpForce = 1f;
    public float gravity = -9f;

    void Awake()
    {
        controller = GetComponent<CharacterController>();
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        grounded = controller.isGrounded;

        if (grounded && velocity.y < 0)
        {
            velocity.y = -0.1f;
        }

        Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0);
        move *= speed;

        if (move != Vector3.zero)
        {
            gameObject.transform.forward = move.normalized;
        }

        if (Input.GetButtonDown("Jump") && grounded)
        {
            velocity.y += Mathf.Sqrt(jumpForce * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        Vector3 totalMovement = (move + velocity) * Time.deltaTime;
        controller.Move(totalMovement);

        HandleAnimation(move);
    }

    void HandleAnimation(Vector3 move)
    {
        if (move != Vector3.zero)
        {
            animator.Play("Walk");
        }
        else
        {
            animator.Play("Idle");
        }
    }
}
coral ivy
#

it seems to work fine. Maybe the collider is too small for my player or maybe the player collider is too large.

wintry quarry
wintry quarry
#

In fact it's not logging anything based on this code

slim salmon
wintry quarry
wintry quarry
slim salmon
wintry quarry
#

something like that

warm mason
#

so why is the player controller thing messsed up like this i cant figure it out and im a dumbass pls help d;

#

if i edit the height, its below the player?

wintry quarry
#

And set this to Pivot mode

warm mason
#

@wintry quarry Thank you, I did that but it seems like its the same issue. Basically im trying to fix this because on game start the character is spawning above the floor. I think its because of the player controller but editing the height it still is underneath the character.

wintry quarry
#

your description is not clear

#

show your hierarchy

#

and what components are on each object

warm mason
#

see how the player controller is underneath the character

#

i cant seem to get that to fit AROUND the character

wintry quarry
#

on the child object(s)

#

delete them

warm mason
#

these two are just the capsule and cube that create the front facing of the character

wintry quarry
#

what components are on it

#

show its inspector

warm mason
wintry quarry
#

I said***

#

delete that capsule collider

warm mason
#

I see i see

wintry quarry
#

and set the position of this capsule object to 0

#

you have it offset by y = 1

warm mason
#

its at 1 because thats the position it needs to be to be above the plane, if not its going to be on the same level as the plane, aka inside

wintry quarry
#

ok

#

then it's fine as is

#

if things look alright visually

#

I think your problem was just the extra capsule collider

#

the box should also not have a collider btw

warm mason
#

ok ok

#

why though, because the character controller overrides it?

wintry quarry
#

Basically CharacterController gets very finicky if there are any extra colliders

#

CharacterController itself is already a capsule-shaped collider

warm mason
#

oh i see what my issue was

#

the center

#

had to be 1 also

#

lol

queen adder
nimble apex
#

is it normal if i made an interface class but does not extend it or inherit it at all

#

but instancing it by doing

private IDialogSteps dialogStepSystem;```
jolly moat
#

I have a SpawnManager game object w/ a SpawnManager script and some empty game objects to represent spawn points for both player and enemies. The player and enemies are prefabs that I spawn on Awake() of the SpawnManager script. It seems like my enemy is walking towards position.x of 0. My EnemyMovement script uses the player's position to drive its direction. Everything appears to be connected properly in the Unity editor. Here's a video of what I'm seeing. I can provide code snippets if that helps.

https://youtu.be/2vTnofNjglc

kindred zodiac
#

Anyone have good resources on setting up a character movement system that doesn't rely on a capsule collision (instead using a mesh collision?)

#

Or explanation

wintry quarry
#

you made a variable

#

also it's just an interface

#

not an "interface class"

rich adder
bold iron
#

Any way of getting rid of "reference not set to the instance of a object" error? I dont know if what im showing is enough and i will show the rest of my script if needed

bold iron
rich adder
#

then you cannot find the object by that name, its not finding. You cant access GetComponent on a null

wintry quarry
#

Also you need to configure your IDE.

#

95% sure it's not configured.

bold iron
#

yea its not configurated

wintry quarry
#

!ide

eternal falconBOT
bold iron
#

ok ill do that

rich adder
nimble apex
#

ok gonna rewrite the whole thing lol

#

ty

bold iron
#

that array contains the dialogue

rich adder
#

npc holds dialogue?

bold iron
#

if i set my reference it means that i will only get one dialogue

#

yea

rich adder
#

should probably make a seperate component for that

bold iron
#

oh

#

my component what is it?

rich adder
#

any script you put on gameobject is component

bold iron
#

on so are you saying that i should create a gameobject with only dialogue script?

rich adder
bold iron
#

the name i assigned for the script i showed?

#

its called npc

#

thats it

#

i could show the whole script

rich adder
rich adder
#

screenshot the heirarchy with this script selected also

bold iron
#

Ok

rich adder
#

btw in meantime configure your ide

bold iron
rich adder
# bold iron

ohh I meant show this but with Dialoguebox gameobject selected

bold iron
#

Ok

rich adder
#

yeah your name is blank

#

no wonder it returned a null object

bold iron
#

Its because im trying to get the name of the npc which i was going to interact

rich adder
#

it would've technically worked but your name in the inspector is BLANK. Its searching for an object with empty string name

#

but still bad practice to search by name. Search by component

bold iron
#

Also you said i shouldnt put dialogue in the npc right?

#

Ok

rich adder
nimble apex
# wintry quarry This isn't instancing anything

how about this

public class DialogSteps
{
    public int steps;
    public UnityAction<string, Dictionary<string, string>> Proceed;
    public Dictionary<string, string> data = new();
}

public interface IDialogStepMethods
{
    public void Init();
    public void InitUi();
    public void OnProceed();
    public void GetInputErrors(string ignoreQuery = null);
    public void IsInputValid();
}

-> usage

class myScript : IDialogStepMethods{
       private DialogSteps dialogStepSystem;
       
       Init(){.....}
       InitUi(){.....}
      ....
}```
wintry quarry
#

myScript implements the interface now yes.

#

you would need to do new myScript() to create one

bold iron
nimble apex
bold iron
#

Or maybe im confusing something else

wintry quarry
#

Note it's not a "gameobject script", it's a Component.

nimble apex
#

ohhhhhhh

rich adder
bold iron
wintry quarry
#

You would need : MonoBehaviour for that as well

rich adder
#

you don't want your scripts to cram different responsibilities in a monolith, gets harder to debug later

nimble apex
#

ok finally knows the approach

#

ty

bold iron
#

Oh

nimble apex
#

👍

bold iron
bold iron
#

Thanks

#

Ok i get it now thanks

drowsy field
#

ive got issues with this line of code when it comes to trying to rotate a rigidbody object toward my mouse position on the screen

because i enabled the cinemachine plugin and used a cinemachine camera for it, it wont rotate toward the exact location of the mouse position, and instead just lazily wobbles around in a seemingly random direction
im not sure is there are other parameters i need to set in the cinemachine camera for this to work properly

there is also a seperate issue with the game playtest locking the mouse and causing this line of code to become unable to perform, so if anyone knows how to make sure i can playtest without locking the mouse, i would also appreciate that

timber tide
#

Cinemachine camera probably fighting with the repositioning of your cursor because you're using screen to world. As the camera moves, so does the pointer position so I expect that be a problem. I think as a bandaid you can just check when the cursor is moved instead of constantly calling this in fixed update

hidden fossil
#

does anyone know like why my turret targets random enemies and not target the enemy closest to the base?

drowsy field
wintry quarry
hidden fossil
#

how would i make it where it targets the enemy closest to base

wintry quarry
#

Have it pick the enemy with the closest distance to the base amongst all its valid targets

hidden fossil
#

thanks!

wintry quarry
#

Without seeing the existing code it's hard to be more specific than that

drowsy field
rich adder
#

0 out the Z

drowsy field
timber tide
#

I'm not entirely sure what you're aiming for here. I'm assuming that the camera pans out towards the cursor, but you're saying it should rotate which I'm not sure what that's about.

rich adder
drowsy field
timber tide
#

So the camera should stay perfectly still, but as you move your gun the camera moves?

drowsy field
timber tide
#

In that case you may be focusing a gameobject with the cinemachine camera which is rotating but instead you want to be focusing on something that doesnt

#

Ok, so then it's not a cinemachine issue?

drowsy field
#

i have no idea what's causing it anymore right now, i got it to work like 5 minutes ago for a brief moment and now it's broken

timber tide
#

I'd retrace your steps and disable the plugin/go back to how you had it and see if it persists

drowsy field
#

ok so when the camera is moving it's what's causing the function to break

#

because when i move the character, the camera moves with it, and the mouse position should just be the same and track with the camera

timber tide
#

I'd probably need to see a video of it and maybe the hierarchy

#

Oh you did post the hiearchy and yeah that's fine

wintry quarry
#

<@&502884371011731486> spam^^

#

(posted in all the code channels)

north kiln
#

!ban 1297220734875340840 spamming

eternal falconBOT
#

dynoSuccess star_firevr was banned.

verbal zinc
#

I have a beginner question for you guys. I'm following a tutorial series and anytime they want to access a gameobject in a script they create a variable for it even if the script is attached to the object we are using.

i.e
Rigidbody rb;
rb =GetComponent<Rigidbody>();

Is there any reason to do it that way compared to just using:

this.GetComponent<Rigidbody>()

when the script your using is only going to be attached to the object you are modifying.

sour fulcrum
#

imagine if everytime you left the house in the morning you couldn't find your keys

#

vs. having them on a little plate or something all the time

#

doing the former avoids having to go find them everytime, even if there's only a couple places it could reasonably be

wintry quarry
verbal zinc
#

Oh i see. It sores the rb in memory instead of having to call for it every time basically.

#

makes sense

sour fulcrum
#

Nitpicking but the rb is stored in memory regardless, what we are storing (called “caching” in this context) is the location of it

wintry quarry
#

Yeah we're storing a reference to the RB in memory.

sour fulcrum
#

Kinda like someone giving you the address to their house

nimble apex
#

how will u guys cut off the repeated code from here?

case 1:
if (!dialogStepSystem.Data.ContainsKey(DialogSteps.DataKeys.SecurityQuestion1) || !dialogStepSystem.Data.ContainsKey(DialogSteps.DataKeys.SecurityAnswer1))
{
    return null;
}
dataForValidate.Add($"security_question{step}", dialogStepSystem.Data[DialogSteps.DataKeys.SecurityQuestion1]);
dataForValidate.Add($"security_answer{step}", dialogStepSystem.Data[DialogSteps.DataKeys.SecurityAnswer1]);

return CustomFunction.SecurityQuestionAnswerValidate(questionInputField.text, answerInputField.text, dataForValidate);

case 2:
if (!dialogStepSystem.Data.ContainsKey(DialogSteps.DataKeys.SecurityQuestion2) || !dialogStepSystem.Data.ContainsKey(DialogSteps.DataKeys.SecurityAnswer2))
{
    return null;
}
dataForValidate.Add($"security_question{step}", dialogStepSystem.Data[DialogSteps.DataKeys.SecurityQuestion2]);
dataForValidate.Add($"security_answer{step}", dialogStepSystem.Data[DialogSteps.DataKeys.SecurityAnswer2]);

return CustomFunction.SecurityQuestionAnswerValidate(questionInputField.text, answerInputField.text, dataForValidate);

case 3:
> same as step 1 and step 2```
nimble apex
#

let me try

wintry quarry
#
var data = dialogStepSystem.Data;
var keys = DialogSteps.DataKeys;

var question = keys.SecurityQuestions[step];
var answer = keys.SecurityAnswers[step];
if (!data.ContainsKey(question} || !data.ContainsKey(answer) return null;
dataForValidate.Add($"security_question{step}", data[question]);
dataForValidate.Add($"security_answer{step}", data[answer]);```
#

that's just a first pass^ there's more you can do no doubt

#

this dataForValidate dictionary and the use of the strings here also seems suspect.

#

Basically any time you find yourself numbering your variables like that (e.g. SecurityQuestion1) you should be using an array or a list instead.

nimble apex
#
    public enum DataKeys
    {
        Username,
        OldPassword,
        Password,
        SecurityQuestion1,
        SecurityQuestion2,
        SecurityQuestion3,
        SecurityAnswer1,
        SecurityAnswer2,
        SecurityAnswer3,
        Phone,
        CountryCode,
        NickName
    }```
wintry quarry
#

I did not expect that to be an enum

#

regardless, put all the enum values you want to process in an array and iterate over it

#

instead of using them individually this way

nimble apex
#

we have multiple steps dialogs, each steps will need u to fill in 1-3 fields, or elements, cause its annoying to let users fill in only one type of data and spam the Next button hard right

i was thinking of containing the data with Dictionary<int,string>, but i cant because of this

#

so i turned to enum

#

and then enum has this issue

#

and yeah i do need to record whats user entered because i need to send it to server for processing

#

but yeah i do get the message, thx

kindred zodiac
#

Like accurate not capsule

verbal zinc
#

Is there any way to get a serializedfield in the inspector to update after adjusting the number in the script?
I've tried playing/stopping etc but the number in the inspector does not update to the new number that was set inside the script.

wintry quarry
#
public int x = 5;``` ^ the 5 here?
#

You would have to Reset the script

#

(... menu -> Reset)

#

that will reset everything on it btw.

verbal zinc
#

Ok yea Rclick-> reset fixes it. I wish it would just update when it reloads the script though....

wintry quarry
#

it would break pretty much every game immediately

#

If you intend for rocketSpeed to never be different on different objects, there's no reason to serialize it in the first place

#

Imagine you set up 500 different rockets with different speeds, and then you changed that one number in the code and you lost all that work

verbal zinc
#

it's mostly just for testing different speeds, But i can forsee how it could cause issues after actually thinking about it.

wintry quarry
verbal zinc
#

I wasn't thinking about other usecases outside of my own haha.

sand mesa
#

hey

#

and I cant seem to get this thing to do the click once

#

instead of going the limit

verbal zinc
#

sorry are you saying your problem is its clicking too many times when you only click once with your mouse?

sand mesa
#

nvm

#

I needed to use GetMouseUp

cloud walrus
#

okay, I'm having two main issues here:

1st: when pressing on spacebar (which is the main key for the spaceship movement) and crashing into an object, the componentmainEngineAudio which is found in Movement file keeps working even though I'm disabling it in CollisionHandler file

2nd: in order to get the audio component OnCollisionAudio working in game, so right before crashing into an object (whether the ground or an obstacle) i need to lift my hand off the spacedbar key to get it working (meaning if i crash into an object while pressing on the spacebar the collision audio won't work (watch the video the understand more)

#

Here are my scripts as well:
``Movement` Script:

using UnityEngine.InputSystem;
public class Movement : MonoBehaviour
{
    [SerializeField] InputAction thrust;
    [SerializeField] InputAction rotation;
    [SerializeField] float thrustForce = 10f;
    [SerializeField] float rotationSpeed = 10f;
    [SerializeField] AudioClip mainEngineAudio;
    
    AudioSource audioSource;
    Rigidbody rbody;
     

    void Start()
    {
        rbody = GetComponent<Rigidbody>();
        audioSource = GetComponent<AudioSource>();
    }
    void OnEnable()
    {
        thrust.Enable();
        rotation.Enable();
    }   
    void FixedUpdate() 
    {
        ProcessThrust();
        ProcessRotation();
        Audioing();
    }
    
    
    
    void ProcessThrust()
    {
        if (thrust.IsPressed())
        {
            rbody.AddRelativeForce(Vector3.up * thrustForce * Time.fixedDeltaTime);
            //Debug.Log("Thrust is pressed");
        }
    }
    
    void ProcessRotation()
    {
        float rotationInput = rotation.ReadValue<float>();
        if (rotationInput > 0)
        {
            ApplyRotation((rotationSpeed * -1));
        }
        else if (rotationInput < 0)
        {
            ApplyRotation(rotationSpeed);
        }
        //Debug.Log($"Rotation is pressed: {rotationInput}");
    }
    
    void ApplyRotation(float rotationStrength)
    {
        rbody.freezeRotation = true;
        transform.Rotate(Vector3.forward * rotationStrength * Time.fixedDeltaTime);
        rbody.freezeRotation = false;
    }
    void Audioing()
    {
        if (thrust.IsPressed())
        {
            if (!audioSource.isPlaying)
            {
                audioSource.PlayOneShot(mainEngineAudio);
            }
        }
        else
            {
                audioSource.Stop();
            }
    }
}```
#

and CollisionHandler Script:

using UnityEngine.SceneManagement;

public class CollisionHandler : MonoBehaviour   
{
    [SerializeField] float delay;
    [SerializeField] AudioClip OnCollisionAudio;
    [SerializeField] AudioClip sucess;
    
    AudioSource audioSource;

    void Start()
    {
        audioSource = GetComponent<AudioSource>();
    }
    void OnCollisionEnter(Collision other) 
    {
        switch (other.gameObject.tag)
        {
            case "Friendly":
                Debug.Log("You've hit Friendly");
                break;
            case "Finish":
                Debug.Log("You've hit Finish");
                audioSource.PlayOneShot(sucess);
                Invoke("DisableMovement", 2f);
                Invoke("NextLevel", 3f);
                break;
            case "Fuel":
                Debug.Log("You've hit Fuel");
                break;
            default:
                Debug.Log("You Crashed!!!");
                DisableMovement();
                PlayCollisionAudio();
                Invoke("ReloadLevel", delay);
                break;
        }
    }
    void ReloadLevel()
        {
            int levelIndex = SceneManager.GetActiveScene().buildIndex;
            SceneManager.LoadScene(levelIndex);
        }
    void NextLevel()
    {
        int levelIndex = SceneManager.GetActiveScene().buildIndex;
        levelIndex++;
        if (levelIndex == SceneManager.sceneCountInBuildSettings)
        {
            levelIndex = 1;
        }
        SceneManager.LoadScene(levelIndex);
    }
    void DisableMovement()
    {
        GetComponent<Movement>().enabled = false;
    }
    void PlayCollisionAudio()
    {
        if (!audioSource.isPlaying)
        {
            audioSource.PlayOneShot(OnCollisionAudio);
        }
    }
}
#

Any help guys?

wintry quarry
cloud walrus
# wintry quarry 1. Disabling the movement script isn't going to make the sound stop playing. the...

thanks for your help i really appreciate that

however there are things i don't undersand,

1st isn't the audio component mainEngineAudio a part of movement script? in other words wouldn't simply disabling the script also disable all the methods / components that are within?

2nd what i understood, the collision sound wouldn't work because there's an audiosource that is already playing mainEngineAudio ig, what's your suggestion to fix that? make another audio source component?

I'm still a beginner in unity btw

wintry quarry
# cloud walrus thanks for your help i really appreciate that however there are things i don't ...

1st isn't the audio component mainEngineAudio a part of movement script? in other words wouldn't simply disabling the script also disable all the methods / components that are within?
No. The movement script simply references the AudioSource component and calls some functions on it. THe AudioSource is still a completely independent component.

2nd what i understood, the collision sound wouldn't work because there's an audiosource that is already playing mainEngineAudio ig, what's your suggestion to fix that? make another audio source component?
Just get rid of the if (!audioSource.isPlaying) check around playing the collision sound. I don't understand why you have it there.

cloud walrus
#

OHHHH

#

thanks a lot!!!

teal viper
cloud walrus
#

this will come in handy ngl

#

much appreciate your help guys

timber tide
#

code it

honest iron
#

how to swim?, i have water(plane) there is nothing under it, i want to keep the head out of the water

teal viper
delicate escarp
#

I want to change this code to use NavMeshLinkData instead of OffMeshLinkData, but I'm not sure how to modify it.....
help

I am using a translator so my reply may be strange or late...

near wadi
#

just spent Way too long at a loss for why my runtime sculpting system was only detecting Back facing vertices, instead of only Front, which i wanted.
Vector3 viewDir = (worldVertex - camPos).normalized;
should have been
Vector3 viewDir = (camPos - worldVertex).normalized;
UnityChanCoder

#

Everything in programming is difficult when you know next to nothing about programming :/

rich adder
delicate escarp
#

I want to convert the code that uses OffMeshLinkData to use NavMeshLinkData instead.

rich adder
delicate escarp
#

ah

rich adder
delicate escarp
#

I see. Then I guess I should change it completely.
I have a lot of questions, but I can't ask many because I don't speak English.
Thank you for your answer.

main gazelle
#
// state
    private enum state {
        AIR,
        WALK,
        IDLE,
        JUMP,
        SLIDE,
        CROUCH,
    }

    private state player_state;

    public void state_manager() {
        if (player_rb.linearVelocity.magnitude <= 0) {
            player_state = state.IDLE;
        }
        else {
            player_state = state.WALK;
        }

        if (Input.GetKeyDown(crouch_bind)) {
            if (player_state == state.IDLE) {
                player_state = state.CROUCH;
            }

            if (player_state == state.WALK) {
                player_state = state.SLIDE;
            }
        }

        if (Input.GetKeyDown(jump_bind)) {
            if (player_state == state.AIR) {
                return;
            }

            player_state = state.JUMP;
        }

        if (player_state == state.AIR) {
            if (!is_grounded()) {
                return;
            }

            player_state = state.WALK;
        }
    }

    public void slide() {
        // early exit
        if (player_state != state.SLIDE) {
            return;
        }

        player_rb.AddForce(transform.forward * 10);
        
        // idk how to check if slide ended
        player_state = state.WALK;
    }

    public void jump() {
        // early exit
        if (player_state != state.JUMP) {
            return;
        }

        player_rb.AddForce(Vector2.up * jump_force);
        player_state = state.AIR;
    }```Heyo, I was wondering if anyone can help me. I am trying to write movement and everyone uses states. I tried some implementation, but it looks wrong the code is hard to maintain cause i have to set and reset states from different functions which becomes incredibly confusing. I was wondering if someone can explain how I could implement something like this. Maybe even provide a code sample. Cause if i want to add even more states it will lead to even more if clauses and confusion.
nimble apex
#
public interface IDialogStepMethods{
    public DialogSteps DialogStepSystem { get; }
}

class A : IDialogStepMethods{
    public DialogSteps DialogStepSystem { get; private set; } = new();
}

this is a valid implementation right?

naive pawn
nimble apex
#

nice

naive pawn
#

(but yes that's most likely valid)

nimble apex
#

finally optimized

timber tide
# main gazelle ```c# // state private enum state { AIR, WALK, IDLE,...

Going to sleep but this is usually what I start with:

public class Player : MonoBehaviour
{
    public enum State { Idle, Walking }
    public State CurrentState { get; private set; } = State.Idle;
    private void Update()
    {
        switch (CurrentState)
        {
            case State.Idle:
                // Idle logic
                break;
            case State.Walking:
                // Walking logic
                break;
        }
    }

    public void ChangeState(State newState)
    {
        if (CurrentState == newState) return;

        OnBeforeChangeState();
        CurrentState = newState;
        OnAfterChangeState();
    }

    private void OnBeforeChangeState()
    {
        switch (CurrentState)
        {
            case State.Idle:
                break;
            case State.Walking:
                break;
        }
    }

    private void OnAfterChangeState()
    {
        switch (CurrentState)
        {
            case State.Idle:
                break;
            case State.Walking:
                break;
        }
    }
}```
elfin locust
#

(https://paste.ofcode.org/V8Tiajh9amwRXRnQZXNz9i)

So rn im trying to implement a jump mechanic where if i jump while moving toward a wall, I slide against the wall since i want to have momentum. This feature was working but I then implemented a feature where if Im jumping while moving forward against a lower object like a cube, I dont gain velocity until my character is above it and able to move forward, since before I was still gaining velocity while not moving causing my character to overshoot the jump.

#

How can i fix/implement this?

placid elm
#

Can someone help me figure this out. I am trying to record a animation with some VFX and shader graph included. I created a cinemachine and started receving hundreds of those error per second and I am not even playing the game

#

apparently restarting Unity helped

rich scroll
#

Yea, sometimes unity gets scared

#

But its been a lot more stable nowadays

raw smelt
#

I am using pooling for my bullets
its that way of implementation of Coroutine is good ?

using UnityEngine;
using System.Collections;
public class BulletData : MonoBehaviour
{
    public float dmg;
    public BulletPoolManager bulletPoolManager;
    private float timeAlive; //place holder if i will add timeDepended DMG 
    private float lifetime;
    private Coroutine destroyCoroutine;
    private void OnEnable()
    {
        lifetime = 5;
        timeAlive = 0f;
        destroyCoroutine = StartCoroutine(DestroyAfterTime(lifetime));
    }

    private void OnDisable()
    {
        if (destroyCoroutine != null)
        {
            StopCoroutine(destroyCoroutine);
            destroyCoroutine = null;
        }
    }
    private IEnumerator DestroyAfterTime(float time)
    {
        yield return new WaitForSeconds(time);
        bulletPoolManager.ReleaseBullet(gameObject);
    }
echo kite
#

how do i make weapon recoil

frosty hound
#

Inb4 "none of them work"

echo kite
#

now i fixed it

#

using ai

frosty hound
#

Lol

#

Good thing AI out here revealing all these tutorials as scams with you at the helm!

low warren
#

hi
i have a problem with my player's ground sliding mechanic
i added some logs to see if the slide is working and the thing that i saw was this: the slide IS working BUT when I press the button the player won't slide, it will stay where it was(but still it can go left or right or jump)
i noticed that the player's movement script is overriding the rb.linearVelocity but i couldn't fix it. i tried to disable the player's movement script in the player's slide script but that didn't work
i also asked this from AI but no it couldn't fix it
anyone can help me?
where can i share the code?

ivory bobcat
#

!code

eternal falconBOT
low warren
#

okay

charred pond
#

Hey guys, Is it real that If I want to pause the game I have only 2 ways:

  1. Time.timeScale = 0f
  2. Create a flag and check everywhere that my game is paused ?
polar acorn
naive pawn
#

which, is a lot of things that move, to be fair

charred pond
polar acorn
low warren
low warren
#

canomeone help me please?

#

can someone*

frosty hound
#

The major issue here is that you have a script for your player's movement which handles normal movement, jumping, wall sliding and wall jumping, then you've decided to, for some reason I can only assume is that you've found this slide code online, seperate another movement state into its own script.

#

Of course if you're going to explicitly set the linearVelocity in both scripts, it's going to take one over the other.

crystal bridge
#
using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(AudioSource))]
public class SoundOnClick : MonoBehaviour, IPointerClickHandler, IBeginDragHandler
{
    public AudioClip clickSound;

    private AudioSource audioSource;
    [SerializeField] private ClickToBig IsBig;  // Reference to ClickToBig script to check IsBig status

    private void Awake()
    {
        audioSource = GetComponent<AudioSource>();
        if (clickSound == null)
        {
            Debug.LogWarning("Click sound not assigned on " + gameObject.name);
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        // If the object is big, do nothing on click
        if (IsBig != null && IsBig.IsBig)
        {
            return;
        }

        // If not big, play the click sound
        PlayClickSound();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        PlayClickSound();
    }

    private void PlayClickSound()
    {
        if (clickSound != null)
        {
            audioSource.PlayOneShot(clickSound);
        }
    }
}

#
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ClickToBig : MonoBehaviour, IPointerClickHandler
{
    [SerializeField] private Vector3 _bigScale = new Vector3(20f, 20f, 20f);
    [SerializeField] private Vector3 _smallScale = new Vector3(5f, 5f, 5f);
    [SerializeField] private bool _isBig = false;
    private RectTransform rectTransform;

    
    [SerializeField] private RectTransform objectToResize;

    
    [SerializeField] private Button closeButton;

    private void Start()
    {
        
        if (closeButton != null)
        {
            closeButton.onClick.AddListener(ShrinkObject);
        }
    }

    private void Update()
    {
        rectTransform = GetComponent<RectTransform>();
        rectTransform.SetAsLastSibling();  
    }

    public bool IsBig
    {
        get => _isBig;
        set
        {
            _isBig = value;
            if (_isBig)
            {
                if (objectToResize != null)
                {
                    objectToResize.localScale = _bigScale;
                }
            }
            else
            {
                if (objectToResize != null)
                {
                    objectToResize.localScale = _smallScale;
                }
            }
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {

        if (_isBig)
        {
            return;
        }
        IsBig = !_isBig;
    }

    private void ShrinkObject()
    {
        
        if (_isBig)
        {
            IsBig = false;  
        }
    }

    private void OnValidate()
    {
        IsBig = _isBig;
    }

    private void OnDestroy()
    {
        
        if (closeButton != null)
        {
            closeButton.onClick.RemoveListener(ShrinkObject);
        }
    }
}
#

I have an object that starts small and when clicked on, it plays a sound and grows big. I tried adjusting the script to disable the OnPointerClick while the object is big so that it doesn't make a sound. While that is the case when big, It doesn't play any sound from the beginning when it is small.

eternal falconBOT
eternal needle
#

📃 Large Code Blocks
in response to your question mark ping. its literally the 2nd line of the bot message

eternal needle
#

thats great. now read the part about 📃 Large Code Blocks
also, add debugs. this isnt some complex logic to follow, you should print out the values or use a debugger and see exactly what values are so you know why you have a problem

crystal bridge
#

Thanks for the help

polar acorn
polar acorn
#

Where do you assign IsBig in SoundOnClick

crystal bridge
crystal bridge
polar acorn
polar acorn
#

And why did you take it out of your if

errant shore
#

yes I just have this

crystal bridge
#
public void OnPointerClick(PointerEventData eventData)
    {
        if (IsBig != null)
        {
            Debug.Log("IsBig.IsBig: " + IsBig.IsBig);
        }

        if (IsBig != null && IsBig.IsBig)
        {
            return;
        }
        PlayClickSound();
    }
polar acorn
#

Also, do you ever expect a situation to come up during normal play where IsBig is null?

#

Will you ever intentionally be leaving out IsBig?

stone ledge
#

How would I perform a raycast in a set range? I've tried spherecast but doesn't seem to work as expected, I just want to raycast for objects in range

#

In a set radius 360 degrees around the character, independant of the camera or angle

polar acorn
#

SphereCast is throwing a sphere and seeing what it hits. CheckSphere is checking what's inside a stationary sphere

crystal bridge
stone ledge
#

Okay I'll try that thank you

#

Oh wow, the checksphere is also alot easier to implement than spherecast

polar acorn
crystal bridge
polar acorn
stone ledge
#

im having issues right now tho

polar acorn
rocky canyon
stone ledge
#

NullReferenceException: Object reference not set to an instance of an object
PlayerInteraction.Update () (at Assets/Scripts/PlayerInteraction.cs:24)

void Update()
{
    Ray ray = new Ray(transform.position, transform.forward);

    bool successfulHit = false;

    Debug.DrawRay(ray.origin, ray.direction * (_interactionRadius * 2), Color.green);

    if (Physics.CheckSphere(transform.position, _interactionRadius))
    {
        Interactable interactable = hit.collider.GetComponent<Interactable>();
        if (interactable != null)
        {
            HandleInteraction(interactable);
            _interactionText.text = interactable.GetDescription();
            successfulHit = true;
        }
    }

    if (!successfulHit) _interactionText.text = "";
}```
#

if (Physics.CheckSphere(transform.position, _interactionRadius))
this line

rocky canyon
#

line 24 references something not assigned or null

polar acorn
polar acorn
eternal falconBOT
stone ledge
#

This was half the script if you dont mind having it here

rocky canyon
#

its a boolean

stone ledge
#

oh

#

then how do i work around this

rocky canyon
#

OverlapSphere has an array of colliders

#

Collider[] colliders = Physics.OverlapSphere(transform.position, _interactionRadius);

#

foreach (Collider col in colliders) {

stone ledge
#

And this works like a radius raycast?

#

If you know what i mean

rocky canyon
#

it grabs everything in a sphere

#

ball..

#

etc

stone ledge
#

That's great

#

Thank you

polar acorn
#

Yeah, Check sphere checks if anything is in range. Overlap tells you what is in range

rocky canyon
#

theres an nonallocated version

#

if u know like a nice limit u wanna use so ur not resizing arrays all the time

polar acorn
stone ledge
rocky canyon
#

like if ur only anting to grab the first of something

#

i dont see why ud need it

#

yea u right digi

#

just figured id mention it

polar acorn
#

It's an optimization, but make it work first, then make it fast

stone ledge
#

I dont carea bout optimizations at the moment I just wanna get comfortable with the different functions

rocky canyon
#

oh, then go hamm 🐖

stone ledge
#

I have a good structure of knowledge when it comes to scripting in gereral it's just getting used to all the different functions

rocky canyon
#

yea, you'll have that for a while

stone ledge
#

Like checksphere. spherecast or overlapsphere, so similar yet very different

rocky canyon
#

autocorrect helps

stone ledge
#

I suppose

rocky canyon
#

start with type u think might use it

#

then just scroll thru all the functions 😉

polar acorn
stone ledge
#

That's useful

polar acorn
rocky canyon
#

also when u hit that optimization part.. use a TryGet as opposed to a GetComponent and null check

crystal bridge
rocky canyon
#

it kinda does both at the same time

polar acorn
rocky canyon
stone ledge
#

Yeah, that's what I thought of aswell when I tried it

#

This is more like it, let's give it a try 🙂

errant shore
#

guys, why does unity load my scene which isnt enabled in build settings

rocky canyon
#

yessir.. looks good at first glance

stone ledge
#

Is GetComponent reliable here? Cause if it doesnt find the component, it'll just be null, correct?

rocky canyon
polar acorn
rocky canyon
#

its fine for now.. TryGets are better tho..

polar acorn
#

That'll cover the situation in which the thing you find doesn't have that component

stone ledge
#

Oh, it's beautiful

#

Works as expected 🙂

polar acorn
stone ledge
#

Thank you

polar acorn
errant shore
#

wait ill show

crystal bridge
polar acorn
# crystal bridge That cannot happen and shouldn't

So, if IsBig is always set, and is not ever intended to be null, then you shouldn't do those null checks. Remove the IsBig != null. If it's ever null, that's a problem and you want to know about it.

#

With the extra null checks, you could have an IsBig not set and literally never know about it and have your buttons misbehaving with no indication

rocky canyon
#

if(mycodeisbroken){KeepItASecret();}

#

been ther.. done that..

#

so, after many systems i realize that depending on how hard i try to structure before hand my scripts typically end up all relying on atleast 2 others.. none minimum, and 3 maximum.. i still find myself having to draw out little flow charts to keep up sometimes.. is this too much still?

#

nothing extravagant mind u.. just isolated things.. like (do this, change ui to this, remember that)

polar acorn
#

Don't get hung up on the number of references, think about the direction of references. Try to keep a sort of "Data flow". You could have a dozen scripts that all reference one central script, but make sure that central script doesn't reference any of the ones lower down

#

Spaghetti Code is not caused by having too many references, but by having too many directions

rocky canyon
#

most all of em have that in common as well

#

they all notify some bigger entity

#

but not referencing any lower downs make sense

polar acorn
#

This is where properties and events come in handy. If a lower-down script changes a variable in a higher-up script, that script can then invoke an event and anything lower-down can subscribe to it and know when it's changed

rocky canyon
#

yessir! 💪 im warming up to events

polar acorn
#

The higher-up script doesn't have any idea about the kinds of things subscribed to it

rocky canyon
#

properties not just yet

polar acorn
#

If, instead of a property, you had public ___ GetSomeVariable() and public void SetSomeVariable(___ value) it'd be the same thing

rocky canyon
#

i'll get there.. but for now it just complicates things in my head. i'll use them sparingly tho

#

it just feels like i end up with duplicates to everything when i try it lol..

#

do you know of any particular system or game feature that i could try out to practice using properties?

#

anything that would make a good use for them

polar acorn
rocky canyon
#

darn.. lol

#

i wanted something that kinda forced my hand.. guess ill have to discipline myself

polar acorn
#

It runs code when a variable changes - that's fantastically useful

#

Have an object's Health variable handle all the checking for death and overhealing all in one

rocky canyon
#

okay yea...

#

i just need to incorporate them into things i already have

polar acorn
#

So you just do Health -= 10 and boom, donezo

rocky canyon
#

b/c i can already find lots of stuff like that ^ yea exactly

polar acorn
#

The property does the rest