#💻┃code-beginner

1 messages · Page 644 of 1

barren wing
#

oka

wintry quarry
# barren wing oka

this is the typical approach:

bool wantsToJump = false;

void Update() {
  if (Input.GetKeyDown(...)) {
    wantsToJump = true;
  }
}

void FixedUpdate() {
  if (wantsToJump && isGrounded) {
    Jump();
    
  }

  wantsToJump = false;
}```
ivory bobcat
#

Poll input in regular update and use the value in fixed update

barren wing
#

it works

#

it stores the Up imput, but it doesnt multiply the impulse

#

works for me :D, ty Praetor

drowsy valve
#

!code

eternal falconBOT
drowsy valve
#

Can anyone recommend some projects to try and make as a complete beginner?

polar acorn
#

Pong

drowsy valve
#

Thanks

obtuse ether
#

trying to code in a thing so that there can be multiple balls in a breakout game

#

im trying to clear a list of gameobjects and then re-add all of the gameobjects still in the game

#

but i keep ending up with an empty element

#

any ideas why its acting funky

polar acorn
#

Are you perhaps running this scan immediately after destroying an object? Destroy doesn't run right away - the object still exists for a little while

#

It might exist long enough to get found by the Find, then gets destroyed

obtuse ether
#

oh

#

i think i probably am running it immediately

#

in a diff script i just delete the ball

wintry quarry
# obtuse ether

instead of using FindObjectsWIthTag, just keep a list of your balls and add them as you spawn them/remove them as they get destroyed

wintry quarry
clever urchin
#

is there any way i can fully delete projects from cloud (not just archive them)? I tried going to my repositories to delete them but it's completely empty there.

fickle plume
#

Archive action mentions that items will eventually be deleted I think.

clever urchin
#

it just says "This project will be disabled across all Unity Services, and the data, files and information associated with it may become irrecoverable."

keen cargo
#

So github desktop question, how do you go back to a certain commit, so in this screenshot the highlighted commit, and then continue from there like the first 2 commits didnt exist/ dont matter?

wintry quarry
grand snow
#

If not pushed you can hard reset backwards, else yea revert them both.

#

well you could hard reset and force push but for a beginner its not a good idea 🤔

keen cargo
#

Do i revert one commit, push, then revert the other, push - or can I revert both at the same time, and then push?

wintry quarry
#

In CLI (IDK how to do it in github GUI):
revert way (creates new revert commits):

git revert <hash1> <hash2>```

The "rewrite history way":
```cs
git reset HEAD~2
git checkout .
git clean -df```
keen cargo
#

alrighty let me see

#

i should learn CLI at some point lol

wintry quarry
#

rewriting history is generally frowned upon so that's why I recommended revert first

#

but if you're alone in the project and especially if you haven't pushed those commits to remote you could rewrite history safely.

grand snow
#

They probably did hence needing to force push but if they fuck it up horribly then bye bye data

wintry quarry
#

yeah I would recommend revert as the safest method, and just get over any angst about a "clean commit history" which has little value

keen cargo
#

so at this point I should be at the highlighted commit basically?

wintry quarry
#

yep!

#

if you want you can select HEAD and that one and do a diff

#

it should be clean

#

I assume github desktop lets you diff two commits through the UI somehow

#

if not you can always do it on the website

keen cargo
#

hmm these are the options

wintry quarry
#

then you'll see a UI with two dropdowns

#

you can paste the commit hashes in those dropdowns

#

to compare them

#

you can also do git diff <hash1> <hash2> in the CLI

#

ideally if we did everything right the diff should be completely empty.

keen cargo
#

hmm it's showing there's some changes

#

yep it's showing there are quite a few changes

wintry quarry
#

which two are you doing the diff between?

keen cargo
#

head and the highlighted commit

wintry quarry
#

What's head? Head only means something on your local machine. Are you doing this on the website?

#

Or you did it locally?

keen cargo
#

I did it on the newest commit vs the highlighted commit on the website

wintry quarry
#

can you show some screenshots?

keen cargo
#

let me see

#

I also tried a test commit to compare against that one as well

#

weirdly enough these two reverts seemed to reverted me back to a somewhat old build of ours

#

uhh i might have found the issue? checking this from the visual studio git history

wintry quarry
#

Here's another option that should work. But... what we did should have worked too.

git checkout ac98601 -- .
git commit -am "Reverting directly to ac98601"```
#

What's in test comm though?

keen cargo
#

it's just a Demo SDF.asset that changes every time you open Unity

#

textmeshpro stuff

#

should be like this right?

wintry quarry
#

Hard to tell until you do the diff again

keen cargo
#

true. one sec

wintry quarry
#

you can just try git diff ac98601 here in the command line

#

it should be empty

keen cargo
#

yep! its empty

wintry quarry
#

yay!

#

ok sorry about the first attempt

#

not sure what went wrong there

#

maybe it was the order of the reverts or something

keen cargo
#

it was super weird yeah, looks like i'll be learning CLI git when i get the time

wintry quarry
#

I'm sure this can be done in the GUI too, it's just what I know is all

keen cargo
#

i think the GUI doesn't give this much control, tried fishing everywhere for info on this kinda thing

wintry quarry
#

yeah the GUI is definitely just a bunch of bindings into the CLI, the CLI has everything.

#

Also different GUIs have different features

keen cargo
#

funny enough my teacher doesn't know how to use CLI git, so he's always impressed seeing my team member use it in front of him lol

could use this to flex as well

wintry quarry
#

haha

#

I guess it's kind of a dying art

keen cargo
#

thanks a lot though!!

wintry quarry
#

No problem, happy coding

prime cobalt
#

For some reason Debug.Log returns a false and the effect never begins playing but no missing reference errors are thrown back and to reach the debug.log it would have to start playing it Sui_Think

slender nymph
#

likely the particle system hasn't actually started playing at this point yet, it probably won't actually start until the particle system component has updated after calling Play

#

or there's a startDelay on it

short fjord
#

hey I was hoping someone could help me with a rather robust and repeating script. My professor has informed me that using serialization or other methods would simplify this code and make it work far better. The game has 3 hallways and every new hallway is a round. The hallways need to reset at the end of every round. Hence the reason I need to change this code. He also showed me a example where I do not need to repeat every method per hallway. if someone can clarify what I should do that would be great! script is :https://paste.mod.gg/opcroimvrbmj/0

prime cobalt
slender nymph
#

are you perhaps invoking the method repeatedly?

prime cobalt
#

I just added a check to see if it's already playing and unfortunately it still doesn't work.

#

nvm I changed it to fixed update and it works now. TowaShrug

snow depot
#

I'm trying to Update my Stamina Bar but I'm getting a Null Reference error.

rich adder
#

unless those unsaved changes and its barImage

snow depot
rich adder
flat holly
#
using UnityEngine;

public class replacescript : MonoBehaviour
{
    public float radius, delay;
    public GameObject replaceObj;

    void OnCollisionEnter(Collision collision){
        explode();
    }

    void explode(){
        Collider[] colliders = Physics.OverlapSphere(transform.position, radius);

        foreach (Collider nearByObj in colliders) {
            Debug.Log(nearByObj.name);
            Collider BC = nearByObj.GetComponent<BoxCollider>();
            if (BC != null) {
                Instantiate(replaceObj, nearByObj.transform.position, nearByObj.transform.rotation);
                Destroy(nearByObj);
            }
        }

        Destroy(gameObject);
    }
}

huh why all dose working but not destroy the nearByObj?

#

i want replace building with ruin for explosion

rich adder
flat holly
#

oh

#

thanks

naive pawn
zinc shuttle
#

Can anyone help me fix this problem, i cant upload or download any changeset from version control

teal viper
zinc shuttle
zinc shuttle
#

it opens cloud.unity with my organisation and project

#

ok unity vcs downloading

zinc shuttle
#

done but, what now, getting same error

teal viper
rapid laurel
#

hellooo, anyone knows how i can select a new font i downloaded?, want to use in a text mesh pro

hexed terrace
#

you need to create a font asset

#

google -> unity tmp how to create font asset

rapid laurel
#

thanks ❤️

fair shore
#
    public GameObject piececontroller;
    private GameObject[] pieces;
    public GameObject slotcontroller;
    public GameObject slotprefab;
    private GameObject[] slots;

    // Start is called before the first frame update
    void Start()
    {
        pieces = new GameObject[piececontroller.transform.childCount];s
        for (int i = 0; i < pieces.Count(); i++)
        {
            GameObject slot = Instantiate(slotprefab, slotcontroller.transform.position, Quaternion.identity);
            slot.transform.SetParent(slotcontroller.transform);
            slots.Append(slot);
            pieces[i].transform.SetParent(slot.transform);
            SpriteRenderer pieceRenderer = pieces[i].GetComponent<SpriteRenderer>();    
            pieceRenderer.sortingOrder = 1;
        }
    } ```
What should I do for my gameobject[] slot to make it not null (or make it null but no ArgumentNullException.)
grand snow
fair shore
#
    public GameObject piececontroller;
    private GameObject[] pieces;
    public GameObject slotcontroller;
    public GameObject slotprefab;
    private GameObject[] slots;

    // Start is called before the first frame update
    void Start()
    {
        pieces = new GameObject[piececontroller.transform.childCount];
        slots = new GameObject[slotcontroller.transform.childCount];
        for (int i = 0; i < pieces.Count(); i++)
        {
            GameObject slot = Instantiate(slotprefab, slotcontroller.transform.position, Quaternion.identity);
            slot.transform.SetParent(slotcontroller.transform);
            slots.Append(slot);
            pieces[i].transform.SetParent(slot.transform);
            SpriteRenderer pieceRenderer = pieces[i].GetComponent<SpriteRenderer>();
            pieceRenderer.sortingOrder = 1;
        }
    }``` Why it creates boxes in a shape of a sword, I want it to put all sprites in the brown box (slotcontroller).
eager elm
fair shore
eager elm
#

Are you using a VerticalLayoutGroup Component for your brown box?
You also shouldn't mess with the scale, instead change the width/height of the image (you might need to unlock it first from a parent component thats driving these values)

fair shore
eager elm
frozen plaza
#

hi!

I have a question about meshfilter and mesh

I need to instantiate a mesh on my object but I need to be able to still access the original mesh. I thought that sharedMesh was always the unedited original mesh but when I set .mesh it also sets .sharedMesh it seems!

can I access the original mesh?

#

and also I don't want to just copy it because it might change (when I resave the source mesh from external for example)

wintry quarry
#

before you change the one on the filter.

snow depot
wintry quarry
polar acorn
snow depot
cosmic quail
polar acorn
frozen plaza
# wintry quarry Save the "original" mesh in a variable.
    void InitializeRuntimeMesh()
    {
        runtimeMeshFilter.mesh = Instantiate(originalMeshFilter.mesh, transform);
        runtimeMeshFilter.name = originalMeshFilter.name + "_Deformed";
        runtimeMeshFilter.GetComponent<MeshRenderer>().enabled = false;

        // Store the original vertex positions and color data.
        originalVertices = originalMeshFilter.mesh.vertices;
        vertexWeights = originalMeshFilter.mesh.colors;
    }

I do this but as soon as I instantiate the original mesh, any changes to the original mash don't carry over any more..

like.. I change some colors on the original mesh in blender, I save it, it doesn't effect anymore as soon as I have this script enabled

#

in fact, as soon as I call Instantiate(originalMeshFilter.mesh, transform); it doesn't work anymore.. why?

wintry quarry
#

if you want the original mesh it should be sharedMesh

frozen plaza
snow depot
#

I'm having difficulty attaching the mouse to unity's New input system. with this setup the Camera doesn't rotate.

wintry quarry
#

also - you should not be multiplying Time.deltaTime on lines 42-43.

snow depot
#

Thank you Praetor!

red wind
#

How do I make fields visible in the inspector but have them greyed out like this? I'm assuming it's an attribute on the field itself, but I looked on the unity docs and couldn't find anything

wintry quarry
#

or use a plugin

#

like NaughyAttributes

red wind
#

Ah OK. Ty for the quick response bongocatlove

hot anvil
#

I have in my prefab, some fruits like banana and apple, and so one... that can increase health of my player. In scene I have multiple instance of them so like apple (1), banana (2), apple (3). I want to create a script that will increase player health based on fruits, by 1 for banana, 3 for apple. In the script how can I know if the gameObject is apple or banana?
I already tried gameObject.name but it return apple (3) if it is the third instance.
I only want to get apple for the condition

rich adder
keen dew
#

Add a script to the fruit objects that tells what they are

#

or even better, tells how much the health increase is

rich adder
#
public class FruitItem  : MonoBehaviour{
public int HealthIncreaseAmount = 1;
}```
hot anvil
rich adder
# hot anvil Can you give more exemple on the Enum?

enum will work but actually thinking about its not going to be very flexible as just passing a value, unless you plan on doing other things
public enum FruitType { Apple, Banana, Orange }
then you would need a variable in the Fruit script to what it is..
public FruitType Fruit = FruitType.Apple; // a default value
but yeah do it like Nitku suggested, something like this
#💻┃code-beginner message

hot anvil
#

Ok I'll try it, thank you guys

wary glade
#

Hello! I am trying to create a random maze generator, I already have the script and prefabs for the walls but how can i bake the navMesh surface for the floor whenever it generates randomly? if it is possible?

naive pawn
mighty citrus
#

Hey! wondering if I could get some help fixing my A*Pathfinder script. For some reason, I keep getting some weird errors in paths where the entity goes backwards?

rich adder
eternal falconBOT
mighty citrus
#

oh sry

rich adder
#

videos need to be mp4 to be embedded

#

if you use remux on obs or just change file ext

mighty citrus
#

thanks @rich adder

#

as you can see, it sometimes goes in a straight line, and others will go a step back then forward

rich adder
#

haven't done own a* algo in a bit so I probably cannot help much.
I would probably first start with visuals. Start with drawing gizmos on the projected path , I'm guessing there is something there being added from your previous thats not suppoed to be there

mighty citrus
#

Yeah I just thought it was a bit too overwhelming and figured Id try myself

#

Something i should note is that it worked fine before adding diagonal movement

#

But I’ll try debugging it with gizmos

stuck palm
#
if (moveDictionary.TryGetValue(evt.newValue, out Move move))
        {

will this out function return a copy of the Move object, or the reference to the move object?

rich adder
#

you're just carrying over an address to that obj

#

here just puts the result in a local variable but its the same object

stuck palm
winter aspen
#

how to name a field differently in inspector?
example:

[SerializeField] private TextMeshProUGUI attackTMP;

I want it to show as "Foo" in inspector while remaining as attackTMP in code.

is that possible?

slender nymph
#

custom inspector could probably do that

winter aspen
#

ohh, there is no built-in attribute such as

[SerializeField][Alias("Foo")] private TextMeshProUGUI attackTMP;

or something of the sort?

north kiln
#

Not that I'm aware of

#

for enum members you can use InspectorName

winter aspen
#

That's unfortunate, thanks for the tip

grand snow
#

Do remember you can also use [FormallySerializedAs] to safely rename a serialized field

winter aspen
#

Thanks ❤️

rotund stone
#

!code

eternal falconBOT
hallow sun
#

I dont think this is a coding issue, but i find it strange that it displays this path after i moved most of my stuf out of the OneDrive folder. This should be C:/Documents

rich adder
grand snow
#

gdrive and dropbox are also a no go

potent birch
#

how do i change the light source to color, im not seeing it in the environment settings in the lighting window, im using hdrp

hallow sun
#

Yeah i hate how OneDrive turns on automatically

green copper
#

if I want the camera to store an enum keeping track of which room it's in, and I want the managers for every room to keep track of what that value is, should I add the camera to every roomManager script, or is there a way I can make the cameraManager script accessible from all my other scripts?

#

like

public cameraManager cameraManager;
in every roomManager is my current plan, setting it in the inspector

wintry quarry
#

it's hard to say for sure without understanding how this system works in your game

green copper
#

currently trying to plan out how it's going to work, so I don't make it stupidly and have to patch it later

Goal is to have six 2d rooms in a 2x3 array, and using the WASD keys pans the camera between them, and rooms like Comms only activate their systems and controls when currentRoom = Comms

#

Camera has the cameraManager script that holds the locations of the camera anchors and controls the wooshy motion between them and stores currentLocation

wintry quarry
#

it can control the camera too

#

or the camera could listen to an event on the ROomManager

#

all the individual compoonents could also just listen to an event on the RoomManager

#

like an OnRoomChanged event

#

which could have arguments for the previous room and the new room

wintry quarry
#

have a virtual camera in each room and you can just switch between them.

green copper
#

can I switch between them with an animation and some 2d parralax effects, or will it just snap the camera as it switches from one to another?

wintry quarry
#

the default is a smooth blend

green copper
#

thanks for the info I'll start reading up on how to use that

#

so for the first part, you're reccomending making a roomManager that holds each room's individual managers in itself, and toggles them on and off when needed?

wintry quarry
#

yes - an array or list of Rooms, something like that

green copper
#

I can tough it out and deal with it if need be, just at a later date, but;

Can anyone reccomend a good text tutorial for using cinemachine? I don't ususally learn very well with video tutorials compared to being able to read it. Plus I don't have headphones for audio for another day

quick pollen
#
foreach(Fade audio in AudioFadeOuts){
            audio.source.volume -= audio.time * Time.deltaTime;
            if(audio.source.volume <= 0)
                AudioFadeOuts.Remove(audio);
}```
is this a safe way of removing audiosources from a list?
Fade is a struct with an AudioSource (source) and a float (time)
#

the idea is that I want to make it so some sounds fade out instead of abruptly cutting out

#

idk if theres a better way for it

#

I keep getting this, but I'm not sure if its a problem

modest dust
#

I'm pretty sure that it is a problem because you'll never execute that code without getting an exception.

cosmic dagger
modest dust
#

You can't modify a list / any collection that you're for-eaching through

quick pollen
#

I mean, I figured

cosmic dagger
#

You must use a reverse for loop . . .

quick pollen
#

ah okay

quick pollen
#

thanks!

quick pollen
#

I'm trying something like this

        if (AudioFadeOuts.Count > 0)
        {
            for (int i = AudioFadeOuts.Count - 1; i >= 0; i++)
            {
                Fade audio = AudioFadeOuts[i];
                audio.source.volume -= audio.time * Time.deltaTime;
                if (audio.source.volume <= audio.maxValue)
                    AudioFadeOuts.Remove(audio);
            }
        }```
#

but I keep getting out of range exceptions

#

even though it shouldnt be possible for it to be out of range like this

cosmic dagger
quick pollen
#

shouldnt it be less than or equal?

cosmic dagger
#

read what you set the loop to do . . .

quick pollen
#

because I want to be able to access -

#

oh

#

fuck

#

right

#

my bad, thank you!

#

shit

cosmic dagger
#

remember, you reversed it . . .

quick pollen
#

yeahhh

#

I just didn't pay enough attention

frigid stump
#

hello! i'm a newbie in gamedev.

so i have made a dialogue system following this tutorial from youtube: https://www.youtube.com/watch?v=DOP_G5bsySA&t=23s
this dialogue system has a button which if u press, will continue to the next dialogue. it also has an animation that "types out" the dialogue.

now i want to use it in a cutscene--which i am animating using a timeline. in this cutscene, characters are moving around and talking to each other. talk first, then move.

i cant seem to find a tutorial on how i can do this. is there any way i can do this? thank you!

grand snow
sharp bloom
#

Does Unity have a feature to serialize a dictionary?

#

Making it public doesn't seem to show up in inspector

sour fulcrum
#

Not by default no

grand snow
ivory bobcat
sharp bloom
#

Okay, I won't bother for now, I can do workaround

#

They should add that feature

jovial grove
#

What is the best method to grow or shrink a character. methods I have tried have not worked with collision detection and have forced the character into the ground or only worked while in the air

sharp bloom
#

What doesn't work with collision detection exactly?

sour fulcrum
jovial grove
#

So when you tried to grow it I think it would grow into the floor or the ceiling so it wouldn’t do it.

sharp bloom
#

I think you need a spherecast or something to check whetever any objects are on the way

#

There's a lot of ways to do this

jovial grove
#

How does unity decide what point to scale from is it the centre of the game object or one of the corners

sharp bloom
#

I think it's always the center

#

You could parent the growing object to an empty gameobject with a position offset if you want a different pivot

#

And scale the parent instead of the original object

#

I've used this method quite a bit but somehow it feels a bit hacky, don't think there's any better way though

#

In Blender you just set the pivot and done

jovial grove
#

Got it working thanks

unborn valley
#

Chat this is probably a really stupid question and i'm probably just an idiot in general but HOW DO I MAKE MOVEMENT RELATIVE TO CAMERA ROTATION

#

Cause i'm trying to make a first person thingy and if i rotate my camera around and press W, it still moves in the "global" forward direction? Idk if i'm explaining myself well

#

Lemme quickly send over my code

#

On the "Player" object:

using UnityEngine;
using UnityEngine.InputSystem;


public class PlayerMovement : MonoBehaviour
{
    [SerializeField] InputAction jump;
    [SerializeField] InputAction movement;
    [SerializeField] Rigidbody rb;
    [SerializeField] Transform cameraTransform;
    [SerializeField] float jumpForce;
    [SerializeField] float moveSpeed;

    private void Start()
    {
        jump.Enable();
        movement.Enable();
        rb = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        ProcessJump();
        ProcessMovement();
        ProcessSprinting();
        ProcessBodyRotation();
    }

    private void ProcessJump()
    {
        float jumpingValue = jump.ReadValue<float>(); 

        if (jumpingValue == 1f)
        {
            doJump();
        }
    }

    private void doJump()
    {
        rb.AddRelativeForce(Vector3.up * Time.fixedDeltaTime * jumpForce, ForceMode.Impulse);
        jump.Disable();
    }

    private void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Floor")
        {
            jump.Enable();
        }
    }

    private void ProcessMovement()
    {
        Vector2 movementValue = movement.ReadValue<Vector2>();

        rb.linearVelocity = new Vector3(movementValue.x * moveSpeed, rb.linearVelocity.y, movementValue.y * moveSpeed);
    }

    private void ProcessSprinting()
    {
        if (Keyboard.current.leftShiftKey.IsPressed())
        {
            moveSpeed = 10;
        }
        else
        {
            moveSpeed = 5;
        }
    }

    private void ProcessBodyRotation()
    {
        transform.localRotation = Quaternion.Euler(0f, cameraTransform.rotation.x, 0f);
    }
}
#

Wow mighty text wall sorry

fossil tree
#

hello, i trying to work in a chess game but that really complicated can someone have some tips for making it ?

knotty wave
#

Guys i have created this script for enemy which can follow my player and shoot but it just goes on following my player everywhere in map i want to set the minimum range so that my enemy only starts following my player when in that range can anyone tell me how to do it please... Here is my script

winter aspen
# unborn valley Wow mighty text wall sorry

look into using the camera's transform

something like this if you're moving on the x,z plane:

Vector3 moveVector = transform.forward * inputMoveDir.z + transform.right * inputMoveDir.x;
        transform.position += moveVector * moveSpeed * Time.deltaTime;
unborn valley
winter aspen
#

yeah

unborn valley
#

Righty

#

Thanks, i'll try

winter aspen
#

my math may be shaky but try it out and see if it works

Basically we use get the camera's forward and multiply that with the scalar value of the forward movement (if negative, this would be back instead of forward).
Likewise for the right movement (which would be left if value is negative).

Left and back are not needed since the scalar would be negative if it is the opposite direction.

Now we use that vector as our direction instead of out global XYZ (default vector3)

unborn valley
#

I think i get what you're saying

#

Though all this stuff is making me dizzy lol

winter aspen
#

yeah it is somewhat "weird" to get haha, I totally get you

fossil oar
#

Quick question for monobehavior singletons, is there a way to always have it added or will I need to spawn the GO in the menu and testing screen if it doesn't exist?

naive pawn
fossil oar
naive pawn
#

well, loaded in addition to other scenes, not added to other scenes

fossil oar
#

ah gotcha! thanks

fair shore
#
  private GameObject[] pieces;
  public GameObject slotcontroller;
  public GameObject slotprefab;
  private GameObject[] slots;

  // Start is called before the first frame update
  void Start()
  {
      pieces = new GameObject[piececontroller.transform.childCount];
      for (int i = 0; i < piececontroller.transform.childCount; i++)
      {
          pieces[i] = piececontroller.transform.GetChild(i).gameObject;
      }
      slots = new GameObject[pieces.Length];
      for (int i = 0; i < pieces.Length; i++)
      {
          GameObject slot = Instantiate(slotprefab, slotcontroller.transform.position, Quaternion.identity);
          slot.transform.SetParent(slotcontroller.transform);
          slots.Append(slot);
         * pieces[i].transform.SetParent(slots[i].transform);
          pieces[i].transform.position = slots[i].transform.position;
          SpriteRenderer pieceRenderer = pieces[i].GetComponent<SpriteRenderer>();
          pieceRenderer.sortingOrder = 1;

      }

  }``` I got a nullreferenceexception at the line where i put the * in.
hexed terrace
#

find out what's null and make it not null.
It's either
pieces[i] or slots[i]

fair shore
verbal dome
fair shore
verbal dome
#

Ah sorry I missed that part

verbal dome
#

Do slots[i] = slot; instead

fair shore
verbal dome
#

Append returns a new sequence with the new item at the end of it, so that does nothing here

hexed terrace
#

The element i in either of those two arrays may be null.

fair shore
sharp bloom
#

Didn't realize there was quite a few of edge cases

#

Works though 👍

tame tusk
#

how do you stop playerprefabs from falling through floor

hexed terrace
#

collisions

vague charm
#

Hello I am trying to make the border to my map but the colliders are too large and take up portions of the map. Is there a way to make them smaller? I've tried several things but i'm lost

wintry quarry
snow flax
#

Hello this maybe a dumb question but is there anyway I can detect collisionExit for character controllers? (Also trying to use OnTriggerEnter but its not working send help plej)

vague charm
#

I see thank you!

snow flax
sharp bloom
#

Is there an event for touchscreens similar to
Mouse.current.leftButton.wasPressedThisFrame

#

Can't find one

#

Oh wait, it's Touchscreen.current.press.wasPressedThisFrame

#

I was missing that "press" in the middle

grand snow
#

Some stuff needs enhanced touch enabled (the docs seem to be quite wrong for the old input -> new input for touch examples)

#

i discovered this all the hard way 😦

green copper
#

What's the general logic over whether to have moving objects and parts moved using physics and velocities and when to use animations?
And when to use animations created in an animation program, vs when to use unity's animation system?

I'm trying to make a clicky clacky satisfying 25 pounder gun loading system in unity 2D, and I'm trying to decide how to implement it

I want the player to use the mouse to click and drag the moving parts to operate the various controls

My current plan is to have the control part give an output in the form of a percent, and have it control movement of the affected parts by an equivalent percent, but I'm not sure if that's optimal or easiest to code

#

In my current system, I can pretty easily do linear multiplicative actions, where a large motion is multiplied by a fraction to make a smaller motion, and I think I can also make it do a logarithmic progressing with accelerating progress but it's convoluted to the point I wanted a sanity check

atomic holly
#

Hello
Is there a way to put a parameter when we assign a method to an action ?
Because, I use the repetitive method to assign the context value of my button for my input system of my game.
My script : https://pastecode.io/s/cjdahyry

wintry quarry
#

I really don't recommend this approach

#

You're introducing a middleman for no benefit

#

and having to write all this boilerplate code.

#

Then for example if another script wants to handle jumping it can just check this in Update:

InputManager.Instance.Input.JumpInput.WasPressedThisFrame()```
#

or it can subscribe to an event itself

#
InputManager.Instance.Input.JumpInput.performed += OnJump;```
#

By trying to centralize all of the input handling and putting it in variables, you have to know ahead of time and in one file how every single input value is planned to be consumed by other scripts, and any time you change something you need to change it in multiple places

#

if you just let the scripts handle things themselves you cut your work in half

#

The only thing this centralized manager should really do is manage the single instance of the generated C# class.

atomic holly
#

Yes, this approach is better I think

#

Thank you very much 👍

unkempt hound
#

Currently doing Unity’s course… Is it worth it?

stuck field
unkempt hound
#

thx

ocean plume
#

ok so I have a very strange and probably basic question. I currently have mouse movement set up using vector and transform localEulers, the camera it works great with no stutter, when I move it to the parent the rotation breaks the rigidbody inerpolation, I want the left right mouse to rotate the character left and right and up down just to rotate the child camera, would I need to add a torque to the player body if so how would that be calculated

wintry quarry
#

in most cases you can just set rb.rotation in place of where you would be setting transform.rotation

cold elbow
#
public void HandleBallCollision(Collider2D collision) {
            
            // Check if the collided object belongs to the ball layer
            if (collision.gameObject.layer == _ballLayerIndex) {
                
                // Ensure that the game logic is properly initialized before updating the score
                if (_gameLogic != null) {
                    // Increment the score of the player based on the collision event
                    _gameLogic.AddScore(1, _playerType);
                    Debug.Log("Score added to " + _playerType.ToString());
                }
                else {
                    // Log an error if the game logic reference is missing
                    Debug.LogError($"Game logic is null in BallCollisionHandler for {_playerType}.");
                }
            }
        }```

For such a long time the condition ``collision.gameObject.layer == _ballLayerIndex`` keeps checking false even tho the objects clearly collide (one goes trough the other, how can I fix this
polar acorn
cold elbow
#
public abstract class BaseBallScannerScript : MonoBehaviour {
        // Reference to the BallCollisionHandler for managing ball collisions
        private BallCollisionHandler _ballCollisionHandler;
        
        // Abstract method to retrieve the player type (e.g., left or right)
        protected abstract PlayerType GetPlayerType();

        // Unity's Start method for initialization
        void Start() {
            // Initialize the ball collision handler with the player's type
            BallCollisionHandler.SetBallLayerIndex(3);
            _ballCollisionHandler = new BallCollisionHandler(GetPlayerType());
        }

        // Unity's OnTriggerEnter2D method for detecting ball collisions
        void OnTriggerEnter2D(Collider2D collision) {
            // Pass the collision event to the BallCollisionHandler
            _ballCollisionHandler.HandleBallCollision(collision);
        }
    }

here

polar acorn
polar acorn
cold elbow
#

none of them

#

that's what confuses me

polar acorn
#

Then at no point is an object with a script that implements BaseBallScannerScript ever have a trigger interaction with an object whose layer is equal to _ballLayerIndex

#

Consider putting in some debug logs to find out at which point something you aren't expecting is happening

cold elbow
#

what do you mean by trigger interaction?

polar acorn
cold elbow
#

oh I see so it means they don't really have to collide with each other

#

like not passing trough each other

polar acorn
#

A trigger is specifically a collider that doesn't cause a collision

#

It's not solid, things pass through it. It detects if it overlaps a collider instead

cold elbow
#

oh ok

#

thanks

#

last time when I made flappy bird the condition condition was true and it was rather a box collider 2D here I used edge collider idk it's related or no

polar acorn
#

Before trying to guess at solutions, you should find out what the problem is. Check if the function is being called at all, and if it is, check the object's layer and what _ballLayerIndex is set to

earnest wind
#
Collider[] results;
    public float checkRadius;
    private void CheckGround()
    {
        int hitCount = Physics.OverlapSphereNonAlloc(transform.position, checkRadius, results);

        isGrounded = hitCount > 0;
    }
#

Why would this not work?

polar acorn
#

What doesn't worrk about it

earnest wind
polar acorn
#

What calls CheckGround

earnest wind
#

the transfrom is at the feet

earnest wind
#

it used to work when i was doing a single raycast down

polar acorn
#

Where do you create results? What size is the array?

earnest wind
polar acorn
#

But you need to create it somewhere

#

that's the point of using NonAlloc

#

it reuses an array

earnest wind
#

so i can just do this?

Collider[] results = new Collider[1];
#

or does it have to be bigger

polar acorn
#

If the length of the buffer is 0, then it will never return anythign greater than 0

earnest wind
#

oh so 1 is enough right?

polar acorn
earnest wind
#

sorry if i didnt understand the question 😭

#

but yeah if there is more than 1 detection it means its on ground

polar acorn
#

If you just want to see if anything is in the area, and don't care what it is, why not use CheckSphere

polar acorn
#

Allocate what

#

it returns a boolean

earnest wind
knotty wave
slender nymph
#

!code 👇

eternal falconBOT
ocean plume
#

I have added the horizontal movement axis to my camera movement and it has a nice smooth rotation whenever you go from a standstill however going from one directon to the other is instand and jarring?
"""cam.localEulerAngles = Vector3.Lerp(cam.localEulerAngles, new Vector3(camRotate.x,0,Input.GetAxis("Horizontal")*-5), camSpeed);"""
should I just have a seperate value and use movetowards or is there some other issue

wintry quarry
#

Lerp doesn't account for the "wraparound" effect that angles have

cosmic quail
wintry quarry
#

also transform.localEulerAngles is liable to suddenly switch from one equivalent representation to another (there are infinite equivalent euler angle representations)

#

You're better off using Quaternions here and RotateTowards or Slerp

knotty wave
#

ok i will give it a shot

knotty wave
knotty wave
cosmic quail
cosmic quail
knotty wave
#

or need i also need to define it?

cosmic quail
#

or Vector2.MoveTowards

#

you've used it in your script already

knotty wave
knotty wave
cosmic quail
knotty wave
#

i tried but no it is not

#

i tried lowering the range and also increasing but no it dont work

#

I thought the same at start that there was no mistake but i am not getting what to do exactly

cosmic quail
knotty wave
#

nice idea i will see

knotty wave
knotty wave
green copper
#
 public enum RoomLocation
 {
     Menu,
     Comms, Gunnery, Barracks,
     Strategy, Loading, Storage
 }

 private class roomConnections
 {
     public RoomLocation up;
     public RoomLocation down;
     public RoomLocation left;
     public RoomLocation right;
 }

 private roomConnections Menu;
 private roomConnections Comms;
 private roomConnections Gunnery;

 

 void Start()
 {
     //initialize
     Menu.down = Comms;
 }```
#

I'm trying to store the rooms located to the up/down/etc of rooms, and it's not letting me assign the values, I get an error with attempting to assign Menu.down, a RoomLocation variable, to be Comms

#

Wait I just realized my error I am a fool I used the same names twice

wintry quarry
cosmic dagger
wintry quarry
#

But it would be like Menu = roomConnections.down; for example

#

That would compile

#

No idea if it makes sense in your concept here though

#

Everything seems confused here

green copper
#

I also missed the part of the code block that included public RoomLocation cameraLocation, importantly, I may just need a break before my brain completely turns to soup

#

Sorry for confusion I think I got it

wintry quarry
#

I would also recommend trying to conform to C# naming conventions

#

It should make things a little easier to think about

green copper
#

I should probably print something to pin over my monitor to remember that

wintry quarry
#

For example a class name should start with a Capital letter

green copper
#

if I have public CinemachineCamera[] cameras; is there a way I can refer to a camera as "comms" instead of as cameras[0] in the script? I could just put camera Comms = cameras[0] in Start() but that seems suboptimal

polar acorn
green copper
#

Yeah, that's part of why I thought that solution seemed suboptimal.

I need seven cameras, one per room plus one for the menu, that that won't chance, so it'll be a static list

polar acorn
#

Probably just use cameras[0]

warm coral
#

hey someone on to help me ?

slender nymph
warm coral
#

sorry i first thought my question would be best in scripting, then i sent in unity talk

edgy tangle
#

Method:
CinemachineCamera GetComms() => cameras[0];

Property:
CinemachineCamera Comms => cameras[0];

#

That way you are doing the same thing but are wrapping it with something more readable

astral flame
#

Hi people, if you can help me with an error I have in this, the code does not show any error but if I press the space key it does not do the animation and also does not jump the collider is set with ontriggerenter and exit what is the animation of idle and walk if it works well but the jump does not

#

Here is also a photo of the animator

slender nymph
#

!code
also make sure the conditions are actually what you expect them to be, use logs if you have to

eternal falconBOT
astral flame
#
using System.Collections.Generic;
using UnityEngine;

public class SirenHead : MonoBehaviour
{
    public float velocidad = 10f;
    public float rotar = 10f;
    public Rigidbody gravedad;
    private bool caminando;
    public Animator animator;
    private bool ensuelo = false;
    public float saltarfuerza = 5f;

    void Start()
    {
        gravedad = GetComponent<Rigidbody>();
    }

    
    void Update()
    {
        float moverx = Input.GetAxis("Horizontal");
        float movery = Input.GetAxis("Vertical");

        Vector3 moverse = new Vector3(moverx, 0f, movery);

        transform.Translate(moverse * velocidad * Time.deltaTime);

        float RotarX = Input.GetAxis("Mouse X")*rotar*Time.deltaTime;

        transform.Rotate(0f, RotarX, 0f);

        bool estacaminando = moverse.magnitude > 0.1f;

        animator.SetBool("run", estacaminando);

        if (ensuelo && Input.GetKeyDown(KeyCode.Space))
        {
            gravedad.AddForce(Vector3.up * saltarfuerza, ForceMode.Impulse);

            animator.SetTrigger("saltar");

            ensuelo = false;
        }

    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("suelo"))
        {
            ensuelo = true;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if(other.CompareTag("suelo"))
        {
            ensuelo = false;
        }
    }
}
slender nymph
astral flame
slender nymph
#

okay and have you added any logs yet?

astral flame
#

no

slender nymph
#

well then do that. also when sharing code, please either use a bin site that will actually automatically add syntax highlighting or have the courtesy of selecting the correct language so that it is added. big gray blobs of text are ass to read

dapper ibex
#

im trying to make a game where hitting a plane with a bullet makes the bullet split off into shrapnel. further hits by the shrapnel also create more shrapnel. my code works when the bullet hits a plane, but when a shrapnel hits a plane the next shrapnel has no force. also debug.log doesnt work in the secondary shrapnel and idk why. heres my code: https://paste.mod.gg/qeikmzkxikgj/1

would really appreciate any help been trying to solve this for a while

cosmic dagger
#

It should run as soon as the shrapnel is created . . .

sour fulcrum
#

start will be a frame later, no?

dapper ibex
#

i debug logged it and the object is active

#

at least on the frame that it is created

cosmic dagger
#

and you don't receive the, "Force applied . . ." debug at all?

dapper ibex
#

nope

#

in the game the new shrapnel just falls and has no force too

cosmic dagger
#

If that's the case, then the Rigidbody component should be null as well. Check if the rb field is null or assigned . . .

#

Oh, it's private; add [SerializeField] in front of private Rigidbody rb; to see it from the inspector . . .

dapper ibex
#

it doesnt come up for some reason

#

but the collider and script are not checked

cosmic dagger
#

What doesn't come up?

dapper ibex
#

the check box thing

cosmic dagger
#

No, you should see the variable rb appear in the inspector under the script . . .

dapper ibex
#

oh i see

#

yeah it shows up

cosmic dagger
#

Now play and check if the secondary shrapnel has their Rigidbody component assigned . . .

dapper ibex
#

they do

#

looks like this

cosmic dagger
#

This happens during gameplay?

dapper ibex
#

yea

cosmic dagger
#

Then the log will appear. They both happen within the same method . . .

eager spindle
#

shrapnel prefab is a clone

#

is this supposed to happen

dapper ibex
#

it happens for the first shrapnel but not the second

#

showing up in log

slender nymph
#

why are the components disabled?

cosmic dagger
#

Are your logs stacked?

#

Does the end of the log have a number bigger than 1?

dapper ibex
#

i checked it only increases for the first shrapnel

cosmic dagger
#

I was just going to ask why the components are disabled as well . . .

dapper ibex
#

idk 😭

#

theyre active for the first shrapnel

cosmic dagger
#

Because if the component is assigned, then the log will appear. It just doesn't make sense otherwise . . .

slender nymph
#

are you doing something silly like cloning a scene object rather than a prefab?

cosmic dagger
#

Are you cloning . . . damn, box is on it . . .

dapper ibex
#

i think im just instantiating another prefab

cosmic dagger
#

Which object is placed in shrapnelPrefab?

#

Are both scripts using the same prefab?

dapper ibex
#

pretty sure

cosmic dagger
#

You need to check. This doesn't tell us if they are or not . . .

dapper ibex
cosmic dagger
#

Can you show us the console logs (after the shrapnel splits)?

#

Place this log at the top of Start . . .

Debug.Log($"Start called on <color=yellow>{name}</color>");
dapper ibex
cosmic dagger
dapper ibex
#

0 (clone) and 4 (clone)(clone)

slender nymph
#

(clone)(clone) means you're cloning something in the scene

dapper ibex
#

ye i didnt do a good test

#

let me try again

cosmic dagger
#

You're instantiating the wrong object then . . .

#

Look at the log. The name of all the instantiated clones are Shrapnel(Clone) . . .

#

But you said you have 0 of those and 4 (Clone)(Clone) GameObjects . . .

dapper ibex
#

nah i messed up the test thats on me

#

let me send a screenshot

#

sry

slender nymph
#

is the ShrapnelScript component attached to the Shrapnel prefab?

dapper ibex
#

yes

slender nymph
#

so that would be why. when it is instantiated the shrapnelPrefab variable gets updated to point to itself because all references to its own prefab get updated on instantiation

cosmic dagger
# dapper ibex

Did the log appear for the correct number of shrapnel?

slender nymph
#

so when the first instantiated prefab goes to instantiate another it ends up just cloning its self

dapper ibex
hidden fossil
#

does anyone know how do you make a linerenderer stay on top of an image or canvas?

dapper ibex
#

so do i have to create another object or is there another way i can do it

slender nymph
#

something instantiates the object at runtime so have that object just pass the prefab to the instantiated objects so it isn't just a chain of them cloning themselves

#

or instead of having shrapnel instantiate shrapnel, have something else instantiate the shrapnel

hidden fossil
#

nvm

dapper ibex
#

ok i see thank you

#

so the prefab is referencing the shrapnel that was already made so instantiating it just makes more copies of that object?

slender nymph
#

no the prefab references itself, so when it is instantiated that variable is updated to reference itself (the newly instantiated object)

dapper ibex
#

it works now thank you

#

wait since i am making 2 shrapnel each collision, each shrapnel should get a different prefab passed down to it right?

slender nymph
#

they just need to have the actual prefab passed to them if they are instantiating the prefab as well. it doesn't have to be different ones, it just has to be the actual prefab asset

slender nymph
tacit torrent
#

Can't convert a double to float?

for(var i = 0;i < RadialCount;i++){
            BasicBullet p = Instantiate(projectile, transform.position, transform.rotation);
            p.transform.Rotate(0.0f,0.0,(float)360/RadialCount);
        }
#

Everything else is working but I don't know how to make the 360/RadialCount float if that doesn't work.

#

Wait nvm it's argument 2 I forgot to put f after the literal

#

Should I delete a question if it's no longer necessary to avoid cluttering the chat

slender nymph
eternal falconBOT
tacit torrent
#

Is this the problem

#

I installed it though

#

With the popup

rich adder
tacit torrent
#

Oh

#

I see

astral flame
#

@tacit torrent Hey, it's better to use Visual Studio 2017 to 2019, that one works very well, especially on a laptop with a Pentium Dual Core T4500 and 4 GB of RAM.

tacit torrent
#

Probably would work better... But then I would have Visual Studio and VS Code

astral flame
#

But to avoid complications, use the 2017 or 2019

#

The vs code does work but it's not the same, really.

naive pawn
#

well of course it's not the same lol

#

personally i find vscode to be plenty, so if you're already used to it, may as well just use that

flat holly
#

in lua i can define WHO to collision enter, how do i do it in unity then?

local obj = workspace.obj

obj.Touched:Connect(function()
  print("touched")
end)
void OnCollisionEnter(Collision collision)
{
  //??? how do i even define which obj to collision detect
}
slender nymph
#

you can use an if statement and things like CompareTag, GetComponent, etc to check what you collided with

flat holly
#

but when i use this function which object will detect? script parent?

slender nymph
#

what do you mean?

flat holly
#

like this function uhhh its just a collision detecting i dont see which object is doing it

slender nymph
#

wdym by "which object is doing it"? this is a unity message, it will be called by the engine when this object collides with another (and the other requirements, such as collider and rigidbody existing are met)

flat holly
#

ok i see yeah parent is this GameObject

#

thanks i will try tags and other myself

slender nymph
#

this.gameObject refers to this objects own gameobject, not its parent gameobject

#

i think you may be misusing the word "parent" there

flat holly
#

maybe

novel nymph
gloomy bison
tame tusk
#

how do you install facepunch steamworks...

#

i have no idea what it wants me to do

verbal dome
tame tusk
#

placed unity folder into my project folder

#

fixed

sharp bloom
#

Was wondering if this is bad practice or not, I'm talking about the break condition of +1000 loops

#

This is a band-aid fix of the game crashing if the pathfinding is unable to find a suitable path (gets stuck in the while loop)

verbal dome
#

Show the rest of the script for better context? Mainly LoopAdjacents()

#

There's likely a better way to avoid that

sharp bloom
verbal dome
#

I mean if it gets stuck at the first iteration then it will do 999 iterations for nothing

sharp bloom
#
 private int LoopAdjacents()
    {   
        int lowestFcast = 999;
        GameHex nextHex = gm.gameGrid.gameHexes[current];
        
        foreach (GameHex hex in gm.gameGrid.gameHexes[current].adjacentHexes)
        {
            if (hex.isObscured || hex.evaluated)
            {
                continue;
            }
            
            hex.hCast = (int)Vector3Int.Distance(target, hex.gridPosition);
            hex.gCast = (int)Vector3Int.Distance(current, hex.gridPosition);
            hex.fCast = hex.hCast + hex.gCast;
            hex.evaluated = true;
            if (hex.fCast < lowestFcast)
            {
                lowestFcast = hex.fCast;
                nextHex = hex;
            }
        }
        Vector3Int nextHexPos = nextHex.gridPosition;
        Debug.Log(lowestFcast);
        path.Add(nextHexPos);
        gm.gameGrid.gameHexes[nextHexPos].GetComponent<SpriteRenderer>().color = Color.green;
        current = nextHexPos;
        return lowestFcast;
        
    }
verbal dome
hidden marten
#

!code

verbal dome
#

Return true only if anything was found

eternal falconBOT
verbal dome
#

When it returns false, break the while loop

hidden marten
#

https://paste.mod.gg/qfwicezbtatl/0
this is my wallrunning script.. for some reason, when i walljump (adding force to up and normal direction), the force to the normal of wall is not added properly... the u force works alright but the normal force is not added. it rubber bands me back to the wall. i've been stuck for a week, any help would be appreciated

sharp bloom
naive pawn
#

but im not seeing what the loop actually does tbh

sharp bloom
naive pawn
#

have you tried to implement more classical pathfinding algorithms?

#

like bfs i mentioned before, aka floodfill

sharp bloom
#

Ye I should, I just recently had a CS class about them

paper meadow
#

Hello, I wanted to create an inventory system for my game. I already have a sword object in my game that I can hit with a mouse click. I haven't found a video yet where my sword is active in the slot and I can actually use it, and if I haven't selected anything, it just shows my hand. Can someone help me? This is a very important matter.

red igloo
blazing solar
paper meadow
#

Yeah i think im very lost at the moment and I think some tutorials are just to complicated or dont have the same as i Do

#

Inside of the Player (The Child) is my Sword object

#

I want to make the inventory so open that I can add a shop where items are added to the inventory. In most tutorials, there's a runner where the items are laying on the ground and you just pick them up, but unfortunately, that's not what I want.

rich adder
paper meadow
#

oh ok if i have a problem i can send it

final kestrel
sharp bloom
#

(I've slowed it down for debug purposes)

azure dust
#

!ide

eternal falconBOT
zenith aspen
#

what does this mean?

polar acorn
zenith aspen
trail rampart
#

So, I am attempting to work on a Top Down Point and Shoot game, but I've been running into an issue with occasional movement stutters whenever I move my mouse.

I put together a very simple project that is just a capsule with a basic movement script and while the dip in FPS is not as prominent as it was in Godot (60 FPS -> 45 FPS compared to 60 -> 7) it still happens.

What am I missing? One small note is that I do have a custom cursor setup as a crosshair.

frail hawk
#

you should probably consider using a phsics based movement instead

polar acorn
trail rampart
trail rampart
polar acorn
sharp bloom
#

It was causing similar issues for me

trail rampart
sharp bloom
#

I have a Razer mouse, I am able to change the polling rate from the Synapse app at least

#

At least 8000 Hz was causing lag for me

trail rampart
sharp bloom
#

I'm not sure

#

It does say this

trail rampart
#

Oi, well.. I have a strong feeling this will fix the issue. I'm a little concerned months of work is going to result in people considering my game not competitive due to weird stutters and asking them to change their mouse settings accordingly, but I guess we'll see.

Thanks Adalwolf et. all for the thoughts and advice

sharp bloom
#

Then again it might not even be the issue :D

polar acorn
#

I think it's your computer

#

Again, check the profiler.

#

If there's a problem in the game, it will be there

trail rampart
#

I believe Adalwolf is on the right track because that was the exact issue the Godot community was talking about, in which Unity was brought up as an engine with a supposed fix. But at the same time Godot ended up having a supposed fixed as well and there are still reports.

It might very well be my computer, but I'd find it odd that this PC would be the issue as I'm not running on anything near a potato.

trail rampart
sharp bloom
#

I feel it's mostly a marketing gimmick anyway

frosty hound
#

Have you tried making this a build and trying it there? Have you tried it on other machines or asked someone else to?

cosmic quail
dusty fern
#

does anyone know what im doing wrong?

slender nymph
#

you need to get your !IDE configured

eternal falconBOT
dusty fern
slender nymph
dusty fern
#

i use vs code

slender nymph
#

great! get it configured.

dusty fern
#

But im not on the same device that i code on

slender nymph
#

what? just configure it on the correct device obviously. having configured tools is a requirement to get help here. and it will make your obvious compile error even more obvious so you can correct it.

dusty fern
#

how do i do that exactly?

slender nymph
dusty fern
slender nymph
#

not unity code

#

it is also very obviously not underlining errors

dusty fern
#

it sends me to the website of vs code

slender nymph
#

with instructions for how to configure it

#

please actually make an effort to read the information instead of looking at the very first thing on the page and making assumptions.

dusty fern
#

it literally just asks me to download it

#

while i already have

slender nymph
#

click the link in the bot embed and it will take you to the page with the instructions for configuring vs code.

#

then once you are there, read that page instead of immediately clicking the "Download" button in the page header which isn't even part of the instructions

dusty fern
#

okay… now im installing the sdk

limber flower
#

i saw some people saying you shouldnt use deltaTime for mouse movements, but i dont remember what they suggested instead, does anyone know?

slender nymph
#

they probably suggested just not using deltaTime for mouse input. there is no replacement for it, mouse input is already a delta from the previous frame so by multiplying it by deltaTime you bind it back to the frame rate and cause it to be stuttery, doing so also forces you to make whatever sensitivity or multiplier variable you are using need to be about 100 times higher

limber flower
#

so instead of
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
do
float mouseX = Input.GetAxisRaw("Mouse X") * sensX;?

#

thank you

summer wren
#

So happy right now. Learned so much today and managed to implement more into the project. Really hope the other collabs will be as happy as I am 🙂

summer wren
#

@limber flower Last time coding was years ago haha. Very excited to be back with it.
Great hobby for sure.

limber flower
#

i just started a few months ago

red wigeon
polar acorn
# red wigeon

Show the inspector of the object this script is on

polar acorn
# red wigeon

Can you expand the Rigidbody inspector and show more of its properties?

green copper
#

is it better practice to have the main game manager to

public CameraController cameraController; and set it in the inspector,

or to

cameraController = FindObjectOfType<CameraController>();```
polar acorn
# red wigeon

Try logging myRigidBody.linearVelocity after you set it, see if the log prints and what it prints

summer wren
#

One thing learned about coding is to stop giving up over frustration. We always get there eventually and it feels great!
Sometimes all it takes is a little more sleep or to step away for a bit haha

polar acorn
red wigeon
green copper
#

I have

public enum playerState
{
    firstLaunch,
    mainMenu,
    loading,
    playing,
    paused
}

public static class GlobalGameStates
{
    public static playerState playerState;
}```

This is so I can keep track of the current state, and do things like check whether the game is paused from any script without needing to individually add the main game manager to every script that might need to check this stuff

Is this a sensible approach? Am I missing any obvious states or problems?
#

my goal is to be able to do things like

if (GlobalGameStates.playerState != playerState.paused)
{
  ##Various time based calculations and stuff that shouldnt     happen when the player is in a menu or reading dialogue 
}
brave robin
#

If you need a monobehaviour for it, but don't want a singleton, then looking into the Service Locator pattern can be a good alternative

green copper
#

What cases might I need a monobehavior for it?
I don't anticipate needing it, the global states thing will hold things like the aforementioned playerState, and also things like the radio status (powerOff, messageWaiting, playerUsing, idle)

The reading and writing will be done by other scripts that are running monobehavior, I'm essentually just using this as a box full of the rare global variables I'll end up needing

#

but I also fully expect I'm missing something, if you can see a case

brave robin
#

A monobehaviour is only needed in this case if you want to have inspector references on the manager. Which it doesn't sound like you need

green copper
#

inspector references? Like being able to go in and manually select "paused" for debugging purposes or something?

brave robin
#

Not so much that, but for being able to drop a reference to your player object, or other important objects, onto the manager
In your case it sounds like you're not handling references to these things in your state manager, and instead its just focused on enums and other raw value data

grand snow
#

well lets not forget about being able to use important functions like Update()

#

But in this situation a plain old class seems like the way to go for generic state storage

brave robin
#

True, the life cycle functions won't be available to a static class. You can "fake" an awake through runtime initialize attribute, but that's it
Though I think this class is storing the variables and not really processing them

tulip stag
#

If my code is like

MyClass
{
  MyMethod
  {
    SomeLogic;
    AnotherComponentInMyGameObject.MethodInAnotherClass;
    MoreLogic;
  }
}```Will my code wait for `MethodInAnotherClass` to finish running before  `MoreLogic` gets called, or since it's in a different component it will run parallel? I ask because in my case `MethodInAnotherClass` could take a while and `MoreLogic` only works if  `MethodInAnotherClass` has run fully.
grand snow
#

er no it waits

brave robin
#

Yeah. There are edge cases where it won't, but that's when you're dealing with coroutines or async

tulip stag
#

Ok perfect!

green copper
#

ah, yeah that's the exact use case. It's storage I'd like to be accessible everywhere. I want the radio to beep every 15 seconds when theres a message waiting, for example

and I don't want it to continue when the player has the game paused

I could drag the mainGameManager script into radioManager and use that to check whether the game is paused, but I'd rather be able to just check if (GlobalGameStates.PlayerState == playerState.playing)

#

because I'll have a lot of objects with scripts like that, and doing so every time would get tedious

brave robin
green copper
#

so keep GlobalGameStates the way it is? where the only thing in there is C# public static ##Some data of some kind

#

or is a "storage class" a seperate thing I'm not aware of

grand snow
#

in c# a static field needs to be declared in a class

brave robin
green copper
#

I currently have those kinds of initializations in the Start() of my main game manager, so I think I'll keep it that way

brave robin
#

Sounds perfectly fine

green copper
#

is there a way I can make the data in that storage class visible for debugging purposes?

grand snow
#

custom editor window?

brave robin
#

Yeah, you could have a custom editor window to display it

green copper
#

I'll look into how to do that, is it complicated?

brave robin
#

Yes and no. If you just need to display variables and don't need it to look nice, then it's pretty straight forward.
Once you want to arrange buttons and have polished presentation, or have complex actions, it can get tricky

grand snow
brave robin
#

I recently made an in-scene level builder for my dungeon crawler using a custom editor window. Took about 2 days

green copper
#

nice!

#

and that indirectly answers my next question, the tutorial said the script had to be in a folder called "editor" but I didn't know if it mattered whether it was "project directory > editor" or "project directory > assets > etc > editor"

brave robin
#

Any folder called "Editor" at any spot will do. The code in there will not compile in builds, and is only available in the editor

#

You can also use compiler directives to specify parts of your code that should only be included for the editor

#if UNITY_EDITOR
// only compiles in editor
#endif
grand snow
#

(except when the folder is in an asm def)

potent birch
#

is there some way i can set up a rigidbody so it isnt affected by external forces but will still collide with other objects

wraith shuttle
#

why that happens ??

grand snow
short hazel
#

You're using older syntax in your code, or Unity is falsely picking up one of your variables from their name and judjes it "obsolete"

wraith shuttle
short hazel
#

Most likely the latter, since that bird tutorial is not ancient

brave robin
#

I learned this lesson the hard way, after not using namespaces

short hazel
#

Post the code so we can see what's going on with it

wraith shuttle
#

and for some reason i dont get unity suggestions

#

idk whats wrong here at all

short hazel
#

The code cannot compile at all (it is invalid) so you should disregard the message until fixed

#

!ide

eternal falconBOT
short hazel
#

^^ Configuration options

wraith shuttle
#

should i just click yes

short hazel
#

No, and configure the code editor first

wraith shuttle
#

how to configure

short hazel
#

Scroll up

wraith shuttle
short hazel
#

"IDE Configuration" message in this conversation above

wraith shuttle
#

i spammed no and it worked

green copper
#
using UnityEditor;
using UnityEngine;
using System.Collections;

public class GameStateInspector : EditorWindow
{
    [MenuItem("Windo/Game State Inspector")]
    public static void ShowWindow()
    {
        EditorWindow.GetWindow(typeof(GameStateInspector));
    }

    void OnGUI()
    {
        GUILayout.Label ("Game States", EditorStyles.boldLabel);
        GUILayout.Label("Player State: " + GlobalGameStates.playerState);


    }
}
#

I think I got it, how do I actually open the window? the tutorial doesn't actually say, it just says it will "create it"

short hazel
#

Using GetWindow should be opening it, if that's not already the case, so make sure this method is being executed

wraith shuttle
#

how to make that star without numpad

#

i started to hate myself already

green copper
short hazel
#

See if you can Debug.Log() in that method

wraith shuttle
short hazel
green copper
#

with your eyes

wraith shuttle
#

not the one that is used

green copper
#

that's just a font

wraith shuttle
#

i have wasd basically qwerty or smth like that

#

im stupid as hell

brave robin
green copper
#

Ah, the fool's "missed a character" type bug, thank you! That got it, works great now!

polar acorn
wraith shuttle
green copper
#

the numpad symbol is also *

#

both * with numpad * with shift + 8

polar acorn
wraith shuttle
#
  • OH SO THAT WORKS
green copper
#

that is a discord formatting thing

#

bullet points are a different thing

sly venture
#

Any idea on why this particular gizmo isn't drawing?

wraith shuttle
#

why im facing everysingle problem idk lol

green copper
#

I would encourage you to read thoroughly and check your available options before asking strangers

short hazel
#

You didn't write the wrong one, it's Discord interpreting a * at the beginning of the line, and displaying it as a bullet point. It's a Markdown formatter

green copper
#

as a general rule that will serve you well in programming

wraith shuttle
#

idk what is rlly happening with me

#

lemme find another recent tut

#

i started to hate that lol i spent 1 hour trying to do simple stuff

#

why i cant find any unity tuts toooo

green copper
#

your first hour with literally any skill is going to be poor, that's typically how skills work

don't assume you have a problem, assume you are missing knowledge, and go forward with that assumption instead

It helps you mentally, in that you don't feel like your computer is trying to kill you

and it helps the people trying to help you, because they feel like you're asking for information and not like you're blaming the program for something

wraith shuttle
green copper
#

example

"wasting 1 hour just trying to find a tut is crazy"

  • is complaining
  • gives the impression you don't want to be here, doing this
  • generally unpleasant and not calm

People here are not being paid to help you and have no obligation to do so

"Can anyone point me in the direction of a good unity tutorial for a beginner"

  • polite
  • more calm
  • still communicates what specifically you need
green copper
#

try this

wraith shuttle
#

thanks brother or sister

green copper
#

Very welcome

General format for asks is something like

I'm trying to [task]

Im doing so by [The specific system or options]

I expect it to [Expected outcome] but instead it [whatever is happening isntead]

and also generally comes with the expectation that you tried to use google first

sly venture
green copper
#

what did you mean by gizmo isn't drawing, anyway?

#

either way, this isn't a code question, it's a general unity question and should probably be somewhere else, like Unity Talk

polar acorn
#

Anywho, I'm assuming it's a custom Gizmo you're expecting to see, post the !code for it

eternal falconBOT
sly venture
#

This gizmo isn't appearing in the editor scene :/. I have tried the following:

  • Reset layout
  • Clicked Gizmo button on/off
  • Ensured default layer is viewable
using UnityEngine;

public class respawnManager : MonoBehaviour
{

    public GameObject objectToSpawn;
    public Transform lineStart, lineEnd;


    // gizmos
    public Color gizmosColor = Color.blue;
    public bool meshPreview;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    private void respawn()
    {
        //respawn stuff
    }
    // Update is called once per frame
    void Update()
    {
       //stuff
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = gizmosColor;
        Gizmos.DrawLine(lineStart.position, lineEnd.position);
        if (meshPreview)
        {
            if (objectToSpawn == null)
            {
                Gizmos.DrawCube(lineStart.position, Vector3.one);
                Gizmos.DrawCube(lineEnd.position, Vector3.one);
            } else
            {
                MeshFilter modelMeshFilter = objectToSpawn.GetComponentInChildren<MeshFilter>();
                Mesh modelMesh = modelMeshFilter.sharedMesh;

                Vector3 modelBounds = modelMesh.bounds.size;

                Gizmos.DrawMesh(modelMesh, 0, lineStart.position, modelMeshFilter.transform.rotation, Vector3.one / modelBounds.x);
                Gizmos.DrawMesh(modelMesh, 0, lineEnd.position, modelMeshFilter.transform.rotation, Vector3.one / modelBounds.x);
            }
            
        }
    }
}

Hope this helps

slender nymph
#

hint: check your color

rich adder
polar acorn
#

Ah, good spot

#

I didn't notice that

sly venture
#

Theres no bot for thank yours here like the web dev discord :/

rugged beacon
#

void abc()
{
othergameobject.setActive(true)
abcxy...
}

is there any scenario that the onEnable in the other gameobject run after the abcxyz

slender nymph
#

no, OnEnable should run immediately upon being enabled via SetActive

rugged beacon
#

okthanks

polar acorn
#

Unless that object has a parent that is still inactive

wraith shuttle
#

what is wrong if someone can tell me

slender nymph
#

you need to get your !IDE configured 👇

eternal falconBOT
wraith shuttle
wraith shuttle
#

i dont have that

slender nymph
#

that may be because you're using vs code not visual studio

#

they are completely different programs

wraith shuttle
#

im using visual studio code

slender nymph
#

that's what i said

wraith shuttle
#

oh thats not it shitto

#

bro i feel stupid as hell

#

what workloads should i add

slender nymph
#

workloads are for visual studio not vs code, did you suddenly switch or are you still looking at the wrong information?

wraith shuttle
#

shouldnt i download visual studio ??

slender nymph
#

i mean it is better than vs code, but you can use either

wraith shuttle
#

then yep i switched to it ig

slender nymph
#

then just follow the instructions in the guide

rugged beacon
#

if you on vsc search the extension place for unity

torn night
#

guys can someone help me: I dont understand why its always a random offset or like its not always hanging the same. It should always be same ledge hanging:

 {
     if (ledgeDetected && canGrabLedge && !isHangingOnLedge)
     {
         canGrabLedge = false;
         isHangingOnLedge = true;

         rb.velocity = Vector2.zero;
         rb.gravityScale = 0f;
         rb.simulated = false;

         Vector2 ledgePos = ledgeDetection.GetLedgePosition();

         Vector2 hangOffset = new Vector2(isFacingRight ? -0.8f : 0.8f, -0.75f);
         Vector2 hangPosition = ledgePos + hangOffset;

         transform.position = hangPosition;

         climbBegunPosition = hangPosition;

         Play(Animations.CLIMB, 0, false, false);
     }

     if (isHangingOnLedge)
     {
         //Play(Animations.CLIMB, 0, false, false);

         if (Input.GetKeyDown(KeyCode.Space))
         {
             PerformLedgeJump();
         }
     }
 }```
eternal falconBOT
wraith shuttle
#

why is it darkened like that

slender nymph
#

because visual studio doesn't know that a component is calling that method so it thinks nothing is referencing it

wraith shuttle
#

oh thanks

#

fr visual studio is lifesaver

#

the other one was trash

#

i actuacctly did wrong code

slender nymph
#

i mean, vs code can do intellisense and error highlighting too provided it is configured

wraith shuttle
#

for me vs code was trash experience

slender nymph
#

because it wasn't configured

wraith shuttle
#

made me give up on two tuts thinking smth was bad experience

wraith shuttle
#

lol cuz i did wrong stuff before the whole project is ruined

torn night
wraith shuttle
#

why velocity doesnt work ??

slender nymph
#

read what it tells you

wraith shuttle
#

it says i should use linear velocity

#

and cuz it is not obsete

slender nymph
#

yes

wraith shuttle
#

but idk how to use linear velocity

slender nymph
#

why not? you know how to spell it, right?

wraith shuttle
#

nvm

#

thanks

#

im very stupid tbh

polar acorn
wraith shuttle
#

u made me learn alot thanks :>

solemn glacier
#

anyone know why i move side to side so fast im new please put it in simple terms

wraith shuttle
#

fr thanks alot guys u helped me in my start cuz im stupid :>

slender nymph
eternal falconBOT
solemn glacier
#

i changed that and it did nothing

polar acorn
#

Did you change it in the inspector

slender nymph
#

change it in the inspector

solemn glacier
#

whats the inspector

polar acorn
#

The place you set variables

solemn glacier
#

should they both be the same

wraith shuttle
teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

solemn glacier
#

thats why the chat says CODE BEGINNER does it not lmao

slender nymph
#

just because it is a beginner channel does not mean you are not still expected to put in effort to actually learn how to use the tools you are using

polar acorn
#

And that's why you've been directed to Unity Learn so you can understand how to use the program

solemn glacier
fickle plume
slender nymph
# solemn glacier thats why im asking questions

and it is also why you've been directed to the unity learn site where you can go through the pathways to learn what everything is and does in a structured way instead of wasting your time waiting on everyone else to spell out every single thing you need to do

teal viper
solemn glacier
#

so since i dont understand how to do something u gotta be a jerk when im still learning

teal viper
#

No one is being a jerk. This common sense really. At least go over the editor ui and the basics of working with it. Then we can move on to fixing your issue.

polar acorn
slender nymph
#

providing resources to learn how to do things yourself is being a jerk?

polar acorn
#

And then you've decided to take offense to that

polar dust
#

The inspector is the thing in the UI where you'd drag scripts onto a game object

swift elbow
teal viper
solemn glacier
#

ok i get your point

teal viper
#

Go learn the basics. It will help you a lot.

#

And us too.

wraith shuttle
#

finished first tut time for 3d tut

#

then some simple projects

#

strange i didnt find any good 3d tut

#

i think time to make the things i want to make

north scroll
#

is there a difference between normalize and clamping ? Dont both set the value on a range basis of -1 to 1 ?

timber tide
#

normalize usually implies taking the full value range and remapping it to a minimum and max, while clamping is just limiting those values

#

like the actual max of the value may exceed the clamp

north scroll
#

so normalize "converts" the full value range into a min max allowing for any value, while clamp firmly restricts going out of range

timber tide
#

Pretty much. Normalizing just makes operations easier when we convert it to some 0-1 range usually

elder osprey
#

How can I create multiple versions of my method? Like how if you use instantiate there are multiple variants with different options for variables.

north scroll
polar acorn
#

Normalizing is also slightly faster than ClampMagnitude for boring math reasons, but it's a negligible amount

north scroll
#

ty

polar acorn
#

Note that this applies to vectors. Normalizing a float isn't really a thing, so a slider value would not be normalized

polar acorn
#

These are called "overloads"

timber tide
#

Screencoordinates are considered normalized, as you're usually dealing with 1,1 top left/right of your sceen and 0,0 being the bottom right / left

#

but vector normalization is something else yeah

rugged beacon
#

if gobj parent is disabled then when parent.setActive(true)
does Start in child or parent get called first or is it just random

#

awake/start/onenable

timber tide
#

if the object you're instantiating is disabled by default, usually those methods won't run

#

as far as start and onenable goes... need to double check the awake

rugged beacon
#

parent is disabled at first in editor, later in the game it get setActive, im not sure the child or parent get called first

timber tide
#

I don't usually rely on the execution ordering of the parent, but if the parent is disabled then the children should also be disabled, so none of those methods should be called anyway

rugged beacon
#

i understand that but later in the game parent get enable back

timber tide
#

Later on yeah they should be called, as far as onenable and start goes

#

onenable -> when the script becomes enabled
start -> first time the script updates

rugged beacon
#

but my main point is does parent's or child's get called first

#

cause when enable parent, child is enable too

timber tide
#

Obviously I'd say parent, but again, I wouldn't rely on the object hiearchy execution ordering.

#

Awake, Start, and Onenabled have their own execution ordering that I would suggest to rely on instead

#

Awake -> OnEnabled -> Start

rugged beacon
#

i think smt thing wrong there, awake should be same order with onEnable?
but parent and child atm can be toggled, so cant settled with awake or start, both use OnEnable, so im just trying to know sure if parent or child get called first

timber tide
#

If you have a chain of dependencies, you can change script execution ordering in the project settings, but I suggest try not decoupling out your objects too much if that happens.

rugged beacon
#

idk, i just wanna kno if parent or child get enable first, if you say parent then imma take ur word for it

timber tide
#

Because I know for sure the ordering of your elements on your scene are order independent for when they execute when loaded, so I wouldn't trust it at all

sour fulcrum
#

yeah fairly sure per instance is unreliable

#

per type can be wrangled if neccasary

elder osprey
timber tide
spark maple
#

Im trying to make a game for a college project 2D platformer and my character wont fall below 0.85 even though my groundcheck is false could anyone help

elder osprey
timber tide
#

overall you shouldnt be spawning an audiosource every time you want to play a footstep. You need to control the source and play it when you need to

timber tide
spark maple
timber tide
#

However, if this is like a small project and you don't care about the absolute optimal setup, I'd say do what works for you

elder osprey
timber tide
spark maple
#

apologies i want my character to fall when approaching an edge but for some reason its y value will not fall lower than 0.85 and float above my groundLayer

timber tide
#

An idea is when you create an audio source for a clip, throw the clip into a dictionary with the previous time played, so next time you play an audio clip you check if its currently in the dictionary and compare against the current time and the time it was last played

elder osprey
twin pivot
#

i moved a script to a different folder and suddenly this happened

#

script in question is not refered to in any other script

timber tide
twin pivot
timber tide
#

Visual Scripting stuff it seems so if you're not using it dont worry

twin pivot
#

looks like unity is just messing with me

#

thanks

timber tide
#
private Dictionary<AudioClip, float> clipCooldowns = new();

public void PlaySound(AudioClip clip, Vector3 position, float cooldown = 0f)
{
    float currentTime = Time.time;
    if (clipCooldowns.TryGetValue(clip, out float lastPlayedTime))
    {
        if (currentTime - lastPlayedTime < cooldown)
        {
            return;
        }
    }

    clipCooldowns[clip] = currentTime;

    //Rest of code
}
#

Just as a fallback, but if you're playing based on a curve then it is dependent on how you play it

cosmic dagger
#

That can be tricky, though. I'm sure some sounds can play more than once at a time. They'd have to figure that out. You could check if the sound (you're attempting to play) is below a max stack limit . . .

elder osprey
#

But I'm thinking, if I were to do what you said and use one audiosource on the camera object, how could I do that and still play the sounds more than once at a time, the time between the sounds and the time between each step need to be proportional.

timber tide
#

Ideal solution: use a single audio source, loop it, and change the audio speed if you need to play it faster

narrow pulsar
#

i have a script that allows the player to jump in my game when it detects tag "ground" it works on a cube but not on terrain

#

does terrain have a diffrent way to detect things or should i just add a box collider to my entire terrain

naive pawn
narrow pulsar
#

alr

#

codes here

slender nymph
#

layers != tags

narrow pulsar
#

ya

slender nymph
#

so think real hard about the question you've asked and what you are actually doing in your code

narrow pulsar
#

the code works when i use a regular cube

#

its in the right tag and all i just switched from a cube to a terrain

slender nymph
#

show the cube then

#

because, again, layers and tags are not the same thing

narrow pulsar
#

ic

#

heres what i had before

#

oh wait not a cube a mesh

#

mb

slender nymph
#

notice how that object is actually on the Ground layer

#

and you aren't doing anything at all with tags in your code

narrow pulsar
#

do you mean like physically touching it

slender nymph
#

no

narrow pulsar
#

the navmesh agent?

slender nymph
#

still no, look at the object you've screenshot. read what your code is doing, read what i've said about tags and layers. then look at the terrain object

naive pawn
#

the code checks for layer ground
the cube is layer ground + tag ground
the terrain is layer [something else] + tag ground

narrow pulsar
#

is this OHHHHHHH

#

OHH

#

DAMN WAIT

#

i may be blind

#

thanks

sour fulcrum
#

Just vibe checking, this works fine right?

        if (SelectedContent is not ScriptableDevice device) return;
        //thing with device
#

dw about the inproper null check

slender nymph
#

provided you are on a unity version that supports that, yes.