#💻┃code-beginner

1 messages · Page 539 of 1

wintry quarry
#
    float scaleSpeed = 1f; // amount to scale per second
    float scaling = 1;

   // Update is called once per frame
    void Update()
    {
        scaling += Time.deltaTime * scaleSpeed;
        transform.localScale = Vector3.one * scaling;
    }```
#

And if you want it to stop at a certain size you would need to put something in to do that

swift crag
wintry quarry
#

e.g.

    float scaleSpeed = 1f; // amount to scale per second
    float scaling = 1;
    float maxScale = 4;

   // Update is called once per frame
    void Update()
    {
        scaling = Mathf.MoveTowards(scaling, maxScale, Time.deltaTime * scaleSpeed);
        transform.localScale = Vector3.one * scaling;
    }```
frosty field
#

wow okay thanks

#

it is working now

wintry quarry
#

Do you understand how it works

#

and why your old code didn't work

frosty field
#

yea.. i kinda forgot how update is also a loop and just making "scaling += scalespeed;" will make it work

#

i thought im gonna be smart or something when i use "for"

#

lol

wintry quarry
#

you could do it with a for loop but it would have to be in a coroutine because that's the only way you could get the loop to pause for one frame each iteration

swift crag
#

Unity doesn't run your code "at the same time" as the rest of the game

#

every frame, it goes through all of your components and calls Update on them, one by one

#

So slightly increasing the size 100 times is just like increasing it by a large amount once

#

All the matters is that, once Unity is done running Update methods, the localScale is bigger than it started

tepid rover
#

I want know all code C# for game 2d

rich adder
coarse shore
#

how does the context menu part work in this ss

#

like when he goes and click "increase score", it increases it but idk how

#

bc it doesnt seem to be connected

#

to the procedure underneath

#

unless it is

wintry quarry
#

I'm not sure why you think it's not connected

coarse shore
#

i mean im new to using c# soo

#

i think its bc its not indented or its not on the same line as the procedure

swift crag
#

Ah, this is an attribute

wintry quarry
swift crag
#

You can attach attributes to various parts of your code -- classes, fields, methods, etc.

#

They're basically little name tags. They have no functionality on their own.

coarse shore
#

ohhhh

#

i see, tysm

swift crag
#

Unity looks for the ContextMenuAttribute on methods and creates a context menu item when it sees one (that's valid, at least)

#

Other common attributes are [SerializeField] (which goes on a field and tells Unity you want a non-public field to still be serialized) and [System.Serializable] (which goes on a class and tells Unity that the entire thing can be serialized, so it'll be saved/loaded and shown in the inspector)

#

Attributes are always attached to whatever "thing" comes next. The whitespace in-between doesn't matter

coarse shore
#

what is a field

swift crag
#

a field is a variable that's part of a class

#
public class Foo { 
  public int field;

  public int Property {
    get { return field; }
    set { field = value; }
  }

  public int Method() {
    return 456;
  }
}
coarse shore
#

imma js learn from the unity thingy atp befoee i start coding 😭

swift crag
#

It's handy to learn the vocabulary, but definitely don't just open the C# language reference and memorize it, ha!

coarse shore
#

i meant the junior course

swift crag
coarse shore
#

i need to learn from scratch

swift crag
#

I originally thought the name was important

#

like, that it had to be done like this

#
[ContextMenu("TheMethod")]
public void TheMethod() {

}
coarse shore
#

yeah i wouldve assume that too

#

what does the "[ ]" do exactly

#

so yk how ' and " is for strings

swift crag
#

That's how you put an attribute in your code

coarse shore
#

i see

wintry quarry
swift crag
#

Here's a class with two attributes on it with a lot of parameters

hybrid gust
#

I'm finding rect transforms incredibly unintuitive. If I just want the Y pos of a rect, how do I do it?

#

getting rect.y is wrong

swift crag
wintry quarry
hybrid gust
swift crag
#

.localPosition is what you want, then

wintry quarry
# hybrid gust local

There's at least:

  • world position
  • local position
  • Canvas space sizeDelta
  • anchored position
swift crag
#

that's where the Transform actually is

wintry quarry
#

You most likely want anchoredPosition I think

coarse shore
swift crag
hybrid gust
#

whats the difference between anchored and local?

swift crag
#

I still can't confidently tell people exactly what to use

#

I do very little with RectTransforms! I let the auto layout system do everything (:

wintry quarry
hybrid gust
#

making a stardw valley esque fishing mini game

#

Gotcha

hybrid gust
#

Cause atp I need to bookmark it

#

and then.. what is rect.y?

wintry quarry
hybrid gust
#

but that ISN'T local?

wintry quarry
#

A rect has no intrinsic meaning. it depends on the context. It's like Vector3

hybrid gust
#

oooh

#

thats..

#

ok

wintry quarry
#

A Vector3 could mean a position in local space, or a world space position, or it could be a set of euler rotation angles.

There's no intrinsic meaning without context.

swift crag
#

This rectangle is in the transform's local space, though

#

So the y value tells how far the center of the rectangle has been moved relative to the RectTransform's origin

swift crag
hybrid gust
#

😕 see I THOUGHT it was the Y in the RectTransform component's Y.

swift crag
#

You could add two dummy objects to mark the two ends

hybrid gust
#

but for that I need localPosition?

swift crag
#

localPosition is the exact position you see in the inspector (when the RectTransform isn't configured to stretch to fill the space of its parent)

hybrid gust
#

Roger

#

Well thank you all

swift crag
#

I'd give the UI docs a read. They're pretty helpful!

#

They also teach you about auto layout. Learning how to use that will make your UIs way more reliable

hybrid gust
#

like the layout groups?

#

oh nvm i see

swift crag
#

I've had to show quite a few people how to use it properly. Part of the problem is that none of the default settings make any sense for auto layout

#

Layout groups are set to not control child size. All of the default objects (e.g. Button) don't ask for any space, so they shrink down to tiny 0 pixel wide blobs

hybrid gust
#

I usually trial and error the auto layout stuff atp lol

frosty field
wintry quarry
#

it's adding 1 to score

#

and then the object is destroyed

#

so it doesn't matter

hybrid gust
#

Does it even add the 1 since its destoryed beforehand?

wintry quarry
#

Each individual instance of this script has its own score

wintry quarry
#

the code will run to completion unless there's an exception.
And Destroy doesn't actually happen until end of frame anyway

frosty field
#

alright but when i put score on top it doesnt work anyway so how to make it count since its getting removed?

#

add one more ontriggerenter?

wintry quarry
wintry quarry
#

It soudns like you didn't read anything I said

#

And you're not understanding this:

Each individual instance of this script has its own score

#

int score; on this scirpt means "each instance of the script has its own score variable"

#

You would want to track the score in one centralized place

#

like a singleton ScoreManager or GameManager script for example

coarse shore
#

does anyone know how to work with a friend on unity?

wintry quarry
coarse shore
#

like im in their organisation

#

and i think im on their project

#

but i dont have the same thign as them

wintry quarry
coarse shore
#

nope, ill go through it now

tawny edge
#

How do i make my character frontflip when he jumps?

I know i should use some for of rotation but i don't know quite how to do it since the methods i used made the character rotate instantly within 1 frame.
Is there a method that makes a rigidbody rotate a specific amount in a axis with a specified amount of time?
Thi is my current project and my current code:

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

public class PlayerController : MonoBehaviour
{
    public float speed = 10.0f;
    public float jumpForce = 50;
    public float gravityModifier = 1.5f ;
   
    public int jumpAmount = 2;
    public float rotationSpeed = 0.1f;
    private Rigidbody playerRb;


    // Start is called before the first frame update
    void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        Physics.gravity *= gravityModifier;
        
    }

    // Update is called once per frame
    void Update()
    {
        Movement ();
        Jump ();
        
        
    }
    // Move player based on arrow key inputs
    void Movement()
    {
        float verticalInput = Input.GetAxis("Vertical");
        float horizontalInput = Input.GetAxis("Horizontal");

        playerRb.AddForce(Vector3.forward * speed * verticalInput);
        playerRb.AddForce(Vector3.right * speed * horizontalInput);
    }

    //Player jumps if spacebar is pressed
    void Jump()
    {
        if(Input.GetKeyDown(KeyCode.Space) && jumpAmount > 0)
        {
            playerRb.AddForce(UnityEngine.Vector3.up *jumpForce ,ForceMode.Impulse);
            jumpAmount -= 1;
            //i want my character to front flip attempt


        }
    }
    // checks if the player collides with the ground and resets the jumpAmount
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.CompareTag("Ground"))
        {
            jumpAmount = 2;
        }
    }
    
    
}


wintry quarry
rugged ferry
wintry quarry
#

Is there any good reason you want or need the actual Rigidbody to flip? That's going to be a lot more complicated for very little tangible benefit

hybrid gust
#

esp if you smack something angled mid flip no?

tawny edge
# wintry quarry Is there any good reason you want or need the actual Rigidbody to flip? That's g...

No specific reason, purely for learning purposes.
For further context, i'm on the very beginings of creating a beatem up as part of my personal project that is instructed to do along with the Unity Learn programming course.
I developer challenged my to add a flip to my jump and i tried to do his challenge with what i learned so far but that has proven to be qquite difficult with what i know now.

swift crag
#

Making the entire physically-simulated object flip around is more complex than just making the player model flip over

tawny edge
#

ok, so wouuld you say that for my purposes of making a beatem up (think Fight'n'Rage, Streets of Rage 4), it wouuld be better iin the long term to do as you say and separate the physic of the player in a separate gameObject and add a child to that that would be used to display the animations???

#

Because if so, then how do i do the next step?

#

i can make a child of the object and uncheck the mesh renderer of the parent, but then i'd imagine id create a script in the child object to make it flip everytime i do a jump? Is that it?

west radish
#

Seems more logical to keep the rigidbody attached to the actual character

tawny edge
#

so, i have this now...
Player Visual is the child object.
How can i make it turn 360 degrees in a axis over a specified period of time?

swift crag
#

This would be a great place to use a coroutine

#

A coroutine lets you write a method that can stop and wait for a while (often one frame)

#

Have a look at that page. You'd just need to adjust the rotation of the player visual instead of changing the color of a renderer

#

(pro tip -- you can use Quaternion.AngleAxis for this)

transform.localRotation = Quaternion.AngleAxis(45, Vector3.forward);

This would give you a rotation of 45 degrees around the Z axis (the blue one)

tawny edge
swift crag
#

The very vague idea is that it's just a method that can stop and resume later

rocky canyon
#

it can do things like wait for end of frame wait x seconds etc

#

can run until a conditional is met, etc etc

rocky canyon
#

all colliders beneath the rigidbody will all be included into a composite type collider (made from multiples)

coarse shore
#

does anyone have footage of someone collabing with someone else in unity. i js wanna see how it looks if its done successfully

long jacinth
slender nymph
#

calling Destroy on an object in a list does not remove it from that list. it just destroys the object (which is done on the c++ side since c# doesn't really have the concept of "destroy). clear the list after you iterate through it and destroy the objects

long jacinth
slender nymph
#

clear the list after you iterate through it and destroy the objects

long jacinth
#

ok

long jacinth
#
foreach (GameObject buildButton in buildButtonDelete)
        { 
            Destroy(buildButton); 
        }

        buildButtonDelete.Clear();

This is what i did and same thing

slender nymph
#

did you save

#

because Clear literally clears the list

long jacinth
slender nymph
#

then show what you are seeing because there is no way that old objects are still in the list after that line

long jacinth
#

when i click on a state

#

when i click on another

pliant abyss
#

When I invoke ScriptableObject.Instantiate in-game to make a clone of that obj, that only lives in memory, and gets deleted when I close the game. Is that correct?

void Start()
{
    ScriptableObject.Instantiate(AnotherScriptableObject obj);
}
slender nymph
rich adder
#

also would check whats inside CopiedBuildingTypes when you add more buttons

humble forum
#

how can i get my cs files in git when i have quite some additions?

rich adder
long jacinth
slender nymph
#

let me guess, the other list was also an array at that time?

humble forum
slender nymph
#

make smaller commits instead of just throwing everything in there

slender nymph
#

well, again, the buildButtonDelete list will only have the newly instantiated objects in it after that method runs

pliant abyss
long jacinth
#

so when should and how should i debug it

humble forum
slender nymph
#

okay, and you can still make smaller commits in your IDE. you are not required to throw everything you've ever changed into a single commit. make your commits actually meaningful so that related changes are together in the same commit instead of having over 12 thousand changes in the same commit

humble forum
#

mostly assets tho 🙂

#

don t wanna make a commit message for just assets

swift crag
#

your game is made entirely out of assets!

#

give every change a clear commit message.

rich adder
humble forum
swift crag
#

the existence of a commit message probably isn't what crashes your version control system..

#

if you're suggesting not putting assets in version control, then that's a great idea until you need to undo any change to an asset

#

at which point your project is bricked

#

You should be able to check out a commit and have a working project, with all of its assets present

humble forum
swift crag
#

oh dear

humble forum
swift crag
#

so your code is version controlled with Git

#

and your other assets aren't?

humble forum
swift crag
#

At that point, you might as well not be using Git at all. You can't go back to a specific commit and get a working project.

humble forum
long jacinth
#
        { 
            Destroy(buildButton); 
        }
        
        buildButtonDelete.Clear();
        Debug.Log(CopiedBuildingTypes);```
#

the message i get

swift crag
#

the ToString method for a list does not show the contents of the list

#

you can iterate over the list and log each item if you want to see that

#

The default ToString just tells you the type of the object

long jacinth
swift crag
#

Seems fine to me

long jacinth
#

did the same thing for the buildbuttondelete and nothing happens

zenith cypress
#

Because it is empty

slender nymph
#

print what is contained in that list at the end of the method to see that it should only contain 2 objects

long jacinth
#

ok

#

There are 2 objects

zenith cypress
#

Is it just one CityManager in the scene, or do you have one per city btw

long jacinth
#

Wait could that be the reason

zenith cypress
#

That is indeed the reason

#

Each has its own list

sleek notch
#

i need help. I don't know why but my code is not working. The 52 is the playerQue.paperQue[0]

spark sinew
#

quick question: how can we make multiple scripts? I have one script to calculate the coordinates and calibrate/print etc for the HUD, but I would like also to move a cube in function of some results of that script. can variables from a script be reused by another script ?

sleek notch
#

and the left picture is all what I had in console

slender nymph
sleek notch
#

for no reason the numb won't be in console

slender nymph
#

make sure you aren't hiding errors or something

sleek notch
#

oh well I'm idiot but why is there error about index out of range when there are 2 objects

slender nymph
#

if 0 is out of range, then the list/array is entirely empty

#

show where you initialize it

sleek notch
#

it can't be

slender nymph
#

prove it

sleek notch
#

alr starting obs

slender nymph
#

just share the code . . .

#

!code

eternal falconBOT
sleek notch
#

I have mutliple refereces by ish 2 scripts

slender nymph
#

okay, so share the code

#

i don't need a video. just the code

spark sinew
# slender nymph it sounds like you want to learn how to *reference* other components. you can do...

Thanks, actually I am wondering, do I need to make two scripts? I just want to change the coordinates of a cube in function of the results of a script that is attached to a camera system. Do I need to create a script that I attach to the cube, and make the variables that I need in the first script global so they can be used by the second script? The issue is what is the order the scripts are run though? For example if the cube script is run first the variable may not even be created

slender nymph
eternal falconBOT
#

:teacher: Unity Learn ↗

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

sleek notch
slender nymph
#

oh god so much static . . .
and of course the one condition you are checking before trying to use the empty list is a public static variable which means any other object could be changing it

swift crag
#

well, and, notably

#
      if (isBuyed != 0)
        {
            
            playerQue.glueQue = 0;
            playerQue.paperQue.Clear();
        } else
        {
            isBuyed = 1;
        }
#

this empties the list up on line 211

sleek notch
#

oh well

#

but then why it is working?

#

I'll show video trust me

swift crag
#

Wasn't the problem that the code isn't working

slender nymph
swift crag
#

It doesn't matter if the list had more than zero elements when that Update method ran. If something changes the contents of the list (e.g. by clearing it), that check is no longer useful.

sleek notch
#

but you was right. Sorry Yesterday I was working on it over 9h until 4am and today also. And the static values they are for saving the numbers between scenes

#

It is for friends last exams in his school

#

so sorry for the unreadable code

tepid rover
proper creek
#

Hi, I'm like really new to programming with C# and unity as a whole, and I am trying to create a unique movement system. I am having a lot of trouble with one specific thing and i'll try to describe it

#

So basically you can only move a rectangle in 4 directions using WASD, and whenever you change directions it comes to a complete stop and have to accelerate again. I want that to happen, but I want it to smoothly slide into the next direction only if you're switching to the opposite direction in that axis.

#

But I can't figure out how to do that and what movement method to use

#

any help would be greatly appreciated, I am really really bad at coding

onyx zenith
#

Hi complete Unity Newbie here. I'm working on an assignment but have been stuck for a while on something really simple, I've created a procedurally generated terrain but can't for the life of me get the collision to work. I've attempted collisions with regular planes with the player character so I know the physics and player collisions are fine and thus must be due to the terrain itself. The terrain has a mesh filter, renderer and collider with the mesh in the filter and collider matching. I'm assuming I've just overlooked something simple so if anyone could point it out to me that'd be appreciated.

swift crag
#

You're generating the mesh yourself, right?

onyx zenith
#

yeah

swift crag
#

ok that question is kind of obviously answered with 'yes'

#

ha

#

I believe you need to do something to get that mesh ready for use with a mesh collider

onyx zenith
#

I've got the options from my script here if there's anything worth noting from it

swift crag
#

Ah

#

But you're manipulating an existing mesh, perhaps?

onyx zenith
#

no the mesh is set to nothing until the project is initiated

swift crag
#

Ah, yep

#

You assign the mesh before you build the terrain

#

So it doesn't get baked

onyx zenith
#

ah

swift crag
#

I think you just need to do this after you're done

onyx zenith
#

ahhhh

swift crag
#

...well, actually

#

just assign it at the end

#

no need to manually call BakeMesh

onyx zenith
#

lemme give it a shot

swift crag
#

this is some weird serendipity, because I only noticed that method a day or two ago

#

after telling someone that I learn about unity quirks by pulling up random autocompletions in my IDE :p

onyx zenith
#

🫂

#

It works

#

thanks so much

swift crag
#

nice!

#

no prob

proper creek
#

does anybody know a solution to my issue 😭

#

i dont mean to be annoying but i just wasted my entire sunday trying to work on it and ive gotten nowhere

pliant abyss
proper creek
#

and im not sure what movement method to use for it

pliant abyss
#

Okay, don't show video or images of code. Your video doesn't play, so I can't tell what is going on.

Show us the code inside triple-ticks ```

eternal falconBOT
vagrant vault
#

Hey I was wondering how to properly use transform.rotateAround

    public static void RotateColumn(ColumnRotateDirection direction, ColumnPosition columntTag, GameObject parent)
    {
        BlockManager[] blockTags = parent.GetComponentsInChildren<BlockManager>();
        List<GameObject> cubesList = new();

        foreach (BlockManager item in blockTags)
        {
            if (item.columnPosition != columntTag) continue;
            cubesList.Add(item.gameObject);
        }

        int degree = GetDegreeToRotateColumn(direction);
        
        foreach (GameObject item in cubesList)
        {
            BlockManager blockTag = item.GetComponent<BlockManager>();
            Transform itemTransform = item.GetComponent<Transform>().transform;

            itemTransform.RotateAround(new Vector3(0, 0, 0), Vector3.right, degree);
            blockTag.UpdateStatus();
        }
    }

I try to make Rubik's cube but when I try to rotate side by 90 degree there is a small problem that some of the cubes dissapears. The problem mainly is in my script that because after each move it check cube position,

    public void UpdateStatus()
    {
        Vector3 position = gameObject.GetComponent<Transform>().position;

        switch (position.x)
        {
            case < 0:
                columnPosition = ColumnPosition.Left;
                break;
            case > 0:
                columnPosition = ColumnPosition.Right;
                break;
            case 0:
                columnPosition = ColumnPosition.Center;
                break;
        }

etc for z and y and mainly reason is in that after some moves one cube have weird position like this. I read something like float estimation (?) but i don't really know how to handle it and where to find answer.
EDIT: I tryed also multiply it by the number very close to one like 0.9999f but after some moves there is visible that this is not 90 degree, but generaly it works

proper creek
timber panther
#

._. my mobs go through walls, i added rigidbody and collider to wall and the mobs but the mob still go through wall

rich adder
#

its likely you're moving mobs through transform instead of rigidbody component

timber panther
#
void ChasePlayer()
    {
        
        // Get the direction from the enemy to the player
        Vector2 direction = (player.position - transform.position).normalized;

        // Move the enemy in the direction of the player
        // Use Rigidbody2D to move the enemy and respect collisions
        if (rb != null)
        {
            rb.MovePosition(rb.position + direction * moveSpeed * Time.fixedDeltaTime);
        }
        else
        {
            Debug.LogWarning("Rigidbody2D component is missing.");
        }
    }

Thats how i move my mobs ._.

rich adder
timber panther
#

so how can i fix it

rich adder
#

you can do AddForce or .Velocity
the direction is the same, just take out the deltaTime

#

also they are localspace so you don't need rb.position+ either

#

so eg rb.velocity = direction * moveSpeed

timber panther
#
if (rb != null)
        {
            rb.AddForce(direction * moveSpeed);
        }

like this right?

rich adder
#

yeah just make sure its inisde the FixedUpdate

winter aspen
#

Hello,
I have a green capsule on my grid to simulate a unit (marked in cyan in the first screenshot). How can I fix this culling issue?
I want it to be "cull if fully invisible" or "dont cull if even part of it is visible"

My camera settings are in the second pic

timber panther
wintry quarry
rich adder
timber panther
#

i use TileMap collider 2D for coliiders

#

and enemy have circle collider

#

they are in Default Layer

rich adder
timber panther
rich adder
timber panther
#

it still go through

rich adder
timber panther
#

i removed rigidbody and composite collider still not work

rich adder
#

its easier to put the gameview / scene view side by side

timber panther
plucky copper
#

This is going to seem like a silly question:

Rider keeps telling me that if (objectThing != null) is an expensive operation.

Is if(objectThing) fully equivalent to checking is something is not null (assuming objectThing is not a boolean)?

rich adder
timber panther
# rich adder are they all at Z of 0 ? also could you send the updated Enemy script in its ent...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Chasing : MonoBehaviour
{
    public Transform player;        // Reference to the player (MainCharacter)
    public float moveSpeed = 3f;    // Movement speed of the enemy
    Rigidbody2D rb;                 // Rigidbody2D component of the enemy

    public LayerMask collisionLayer; // LayerMask to check for collisions with walls/obstacles, not the player
    void Start()
    {
        
        rb = GetComponent<Rigidbody2D>();
        collisionLayer = LayerMask.GetMask("Default");
        // If the player is not manually assigned, find the player by its tag
        if (player == null)
        {
            player = GameObject.FindWithTag("Player").transform;
        }
        // Check if the enemy and player are on the same collision layer
        if (collisionLayer == (collisionLayer | (1 << player.gameObject.layer)))
        {
            Debug.Log("Enemy and player are on the same collision layer.");
        }
        else
        {
            Debug.Log("Enemy and player are on different collision layers.");
        }
    }

    void FixedUpdate()
    {
        // Check if the player exists
        if (player != null)
        {
            // Move the enemy towards the player
            ChasePlayer();
        }
    }

    // Function to make the enemy move towards the player
    void ChasePlayer()
    {
        
        // Get the direction from the enemy to the player
        Vector2 direction = (player.position - transform.position).normalized;

        // Move the enemy in the direction of the player
        // Use Rigidbody2D to move the enemy and respect collisions
        if (rb != null)
        {
            rb.velocity = direction * moveSpeed;
        }
        else
        {
            Debug.LogWarning("Rigidbody2D component is missing.");
        }
    }
}

Also where to find the Z, if it mean the order in layers, ye they all 0

rich adder
#

did you mess with the Layer overrides ? or any of that

timber panther
#

is it the Z in the first line?

#

so ye both in same Z position

rich adder
#

lol dam well there is something obvious I'm missing here..

rich adder
timber panther
timber panther
#

nvm

#

the code work if the rigidbody is dynamic ;D

rich adder
timber panther
#

i set it kinematic

rich adder
#

oof..I forgot kinematic has velocity in 2d..

#

so it moved

timber panther
#

welp

rich adder
timber panther
#

it strange

#

the enemy not moving

#

and my character spinning

#

._.

#

ok i fixed it

timber panther
rich adder
spark sinew
#

I tried to use the trick of math.round() to round a number to a certain number of decimals, but it does not seem to work always

#

for example if I do math.round(x*100f)*0.01f it should round to 2 decimal points

#

however due to float things somethimes I get like 1.099999999999 instead of 1.01

swift crag
#

It will, barring floating-point precision problems.

spark sinew
#

orry instead of 1.10

swift crag
#

If you want to display a number with a certain number of digits, that's a completely separate topic

spark sinew
#

so how should I do for display?

swift crag
#

This will log a number with two decimal digits

spark sinew
#

and to display on a textbox, it would still work ?

swift crag
#
string whatever = $"{myValue:N2}";
spark sinew
#

thx!

swift crag
#

The $"" syntax is called "string interpolation"

#

You don't have to use it -- you can also use String.Format

#

In that case, you'd do something more like

#

string.Format("{0:N2}", myValue)

#

I like string interpolation because you put the value directly into the string

spark sinew
#

ok

swift crag
#

The N means "number", and then 2 tells it to have two decimal digits

short fjord
#

Hey I have some issue with my animations not randomly playing. One of the kick animations DOES play but only that one it wont change. I have messed with the states, ran it through chat gpt, the transitions, and as far as the script i have no clue what is wrong as every transition has the kick trigger except the first one entering the substate machine which has the space trigger. here is the link to my code. and i will attach screen shots of my animator. just to be clear the goal is that every time i press space one of these three animations will play at random. https://paste.ofcode.org/pxrBdbBWqxmyaYR9gveYa3

swift crag
#

What does "not playing" here mean? Does the animator enter the correct state but simply not produce any motion, or does it get stuck and not enter Kicks at all?

short fjord
swift crag
#

Oh, I hard a brain fart

#

I misread that as "Randomly not playing"

short fjord
#

lol yeah i need them to randomly play

swift crag
#

What do the transitions from "New State" to the three kick states look like?

short fjord
#

it is "kick" as the trigger one is kick1, kick2, kick3 which should get shuffled through because of my script? this part in particular

#

int random = Random.Range(1, KickRandomizer + 1);
string triggername = "kick" + random;
KickAnims.SetTrigger(triggername);

swift crag
#

I'm talking about these transition arrows

short fjord
#

thats what im saying each one is just a kick with a different number

swift crag
#

What about this transition into "Kicks"?

short fjord
swift crag
#

Okay, that looks fine

#

You set two triggers: one called "SPACE" that takes you into the sub-state machine, and then a second that takes you from "New State" into a specific kick state

#

I see no reason for KICKED() to not set the three different kick triggers uniformly at random

swift crag
# short fjord

Make sure that each transition uses a different kick trigger, of course

#

and that each animation state has a different animation clip assigned to it

short fjord
swift crag
#

Each animation state has a Motion

#

which is either an animation clip or a blend tree

#

random example

#

this is an animation state named "Scene - Shore" that references an animation clip that's also named "Scene - Shore"

#

check that you didn't assign the same clip to all three states

short fjord
#

they are all different

#

Right now every kick is front kick( when testing it to clarify)

swift crag
#

are you sure you aren't just unlucky? :p

short fjord
swift crag
#

"reset the state machine"?

short fjord
#

i wanted to go add every tranistion and animation back in one by one to make sure i wasnt crazy

swift crag
#

You should log the trigger you're setting in KICKED(), to verify that it's not setting the same trigger each time

short fjord
#

they are all different amd all have the appropriate triggers but now it is front kick it is stuck on

swift crag
#

I don't see any reason for that to happen -- KickRandomizer is private and not serialized, so nothing could be changing it

#

unless you're doing something weird with the rng seed in Random

#

e.g. setting it to a constant value every frame

short fjord
#

ok sooo i think i see what is happening now but i dont why

#

so according to the debug log it does go through other trigger names but the animations dont actually start and once it goes to 3 it stays at kick3 it wont go back to any other

swift crag
#

Ah, so it fails to kick at all until it happens to pick kick3

#

Make sure you don't have any spaces in the names of those triggers

#

I'm pretty sure a trailing space is allowed, like kick1

short fjord
#

OK I GOT IT TO WORK YAYYYYYY now i just gotta adjust all the times

#

THANK YOUUUU\

latent glade
#

How can I make a ray cast start out ahead of the gameobject?
I want to have a bot check to see if there is no ground ahead of it, then it would jump

spark sinew
#

Hi y'all I would like to make a cube appear or disappear, the cube is defined with the tag "Target" in the game. However, when I try to access it Target =GameObject.FindGameObjectWithTag("Target"); it fails (the code doesn't go further

latent glade
#

are going to end up only hiding one cube or multiple?

frosty hound
#

Finding with tags only does so with active objects.

spark sinew
#

I used Gameobject.Find() and now it works. Not sure what was the issue

rugged beacon
#

i just started with unity 6, cant find the package for visual studio code
is it not supported anymore ?

rich adder
#

steps ⬇️

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

rugged beacon
#

thanks thought it was 2 different packages like before

rich adder
#

that nightmare is over

nova swift
#

Hey yall, heard bad things about OnTriggerStay2D, is this approach any better than using that method?

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.layer == 3) isTouchingPlayer = true;
        if (other.gameObject.layer == 11) isTouchingPlayerTwo = true;
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.layer == 3) isTouchingPlayer = false;
        if (other.gameObject.layer == 11) isTouchingPlayerTwo = false;
    }

    private void Update()
    {
        if (isTouchingPlayer) DetectedPlayer();
        if (isTouchingPlayerTwo) DetectedPlayerTwo();
    }
nova swift
rich adder
nova swift
nimble apex
#

is it a good idea to inherit OnDestroy()?

#

or use new

spare mountain
nimble apex
sullen perch
#

cansomewone pls help, i have a script that is ment to turn on a object when it collides but dosent

sullen perch
#

i dont understand

steep rose
#

you need a rigidbody on 1 of the objects

sullen perch
#

i did that but it still dosent work

#

i also added unity.UI

teal viper
polar acorn
sullen perch
#

Hi, I fixed the issue, thanks for all the help

torpid viper
#

Are there premade scripts i can find somewhere

fickle kelp
#

Do I have to pay to use unity?

timber tide
#

no unless you make money, so no

eager spindle
teal viper
torpid viper
#

Well i think il learn faster that way

#

Im still not sure wherever to use ue5 or unity

keen owl
teal viper
keen owl
#

my fault, I didn't even see the type lmao

mighty glacier
#

Anyone know how to fix this lighting issue?

#

It ruins the vibe when the player gets close to a wall or anything

#

There's this huge line of light

keen owl
mighty glacier
#

and soory didnt see that channel xD

keen owl
#

All good lol

flat sphinx
#

how do i get probuilder to be useful

#

all the tutorials use some 2019 version which has a vastly diff ui

#

rn trying to extrude a cube and all the options are greyed out

burnt vapor
#

This channel is for coding questions

flat sphinx
#

huh

onyx zenith
#

anyone have anyguesses as to why popUpPrefab isn't showing up in the inspector?

burnt vapor
eternal falconBOT
teal viper
burnt vapor
#

Until then, we can't/won't help you

onyx zenith
teal viper
onyx zenith
#

is this not configured?

teal viper
frail hawk
#

the white color of MonoBehavoir inside your script shows that you have your IDE not configured correctly. Intellisense and a few things are not working.

#

might be some things related to this why your field is not popping out.

burnt vapor
#

I'd assume it is the workload, but this is up to you to check

#

Alternatively, regenerate your project files

#

It might be configured, just set up wrong by Unity

frail hawk
#

i am guessing you have some errors you have to fix first, they might be not showing up in the console because you have disabled the console log out in Unity

onyx zenith
#

idk what to tell you guys I installed it today and I'm not getting the option to update it or anything

teal viper
#

It's in External tools tab.

onyx zenith
teal viper
frail hawk
#

i know you said popUpPrefab but did you mean popupInstance instead.

burnt vapor
#

Yeah if these things are actually valid it should just work tbh

frail hawk
#

it is private it has to be public if you want it in the inspector

onyx zenith
#

is solution explorer just this where it shows the errors at the bottom?

teal viper
burnt vapor
#

I'd say screenshot the whole window rather than just that

teal viper
onyx zenith
#

what part of that do you need to see it's just the assets folder

#

oh

#

oh my god

#

🫢

#

I'm been editing the wrong script this entire time

#

I'm so sorry

burnt vapor
#

🤔

#

But regardless your editor is broken

frail hawk
#

yeah it is really important to have instellisense function working, especially for beginners, it will support you alot.

burnt vapor
#

The way you send messages makes me wonder if you use ChatGPT for them

frail hawk
#

who you talking to

tawdry quest
#

Noone here looking like GPT

tawdry quest
#

[SerializeField] is the better option, so you dont have everything public

frail hawk
#

sorry but not everyone is a native english speaker like you ...

#

and i do not use gee pee pee.

tawdry quest
#

You want to have as little public as possible (ty autocorrect)

hexed terrace
#

There is never a need to have a public field

tawdry quest
#

Sometimes doing nothing is the better choice

frail hawk
#

dude you are being rude rn for no reason, i only said that because the rest of his fields were also public and one was private..

tawdry quest
#

Im not

hexed terrace
#

No one has been rude

tawdry quest
#

You are free to answer, but if you already say you dont speak good english and are easily misunderstood, then please leave it to people that actually speak english properly.

frail hawk
#

this is rude : Yes, but then please refrain from trying to help, if you cant even understand the problem / answer correctly.

hexed terrace
#

That's not rude.

tawdry quest
#

Its not rude at all

frail hawk
#

for me it is very rude.

hexed terrace
#

¯_(ツ)_/¯

tawdry quest
median anchor
#

Depending on context it's a bit condenscending.

tawdry quest
pliant abyss
# frail hawk this is rude : Yes, but then please refrain from trying to help, if you cant eve...

This isn't rudeness. There is no other way to say convey this thought. It isn't a criticism of your intelligence. Language acquisition is difficult, and English is particularly weird. If others are having trouble understanding you, you are not helping them, especially in a nuanced field like computer science.

It is good that you are trying to help, it is good that you are practicing your English, but beginners don't known everything they need to know and are easily confused. I know because I am a beginner.

timber tide
#

Can't be bothered setting up event handlers on everything

naive pawn
timber tide
#

long live public fields

tawdry quest
hexed terrace
burnt vapor
#

However, this wasn't some indication to start a pointless discussion. My bad for bringing it up

frail hawk
#

it is all good just mad at the kid trying to teach me unity and being rude.

burnt vapor
#

Not sure why people would chime in regardless 🤷‍♂️

frail hawk
#

even explained why i said public there.

pliant abyss
#

Unity Tests

west garnet
#

can i dm anyone?
i got a small school project that i need to do related to code but im so confused and i cant make it work
im very new to code and i feel like my classes are way more advanced that what im able to do

frosty hound
#

You can ask questions here. People aren't going to sit in DMs to personal tutor.

eternal falconBOT
fresh arrow
#

can someone tell me the difference between the usage of Vector2 and newVector2?

wintry quarry
wintry quarry
#

if you mean what is new Vector2(x, y) that's the Vector2 constructor being called

#

The constructor creates a new C# object, in this case a Vector2

fresh arrow
cosmic quail
polar acorn
#

new Vector2 is a thing. You initially said newVector2 which is not a thing

fresh arrow
#

yeah forgot the spacing

#

im writing a script where if the character steps on the objects it jerks upwards but right now it just teleports to y 44 how can i give it that motion?

languid spire
fresh arrow
#

can you explain how would you use it?

languid spire
#

Is this some kind of yoof code for 'I cant be arsed to look things up'?, I see this response so often
instead of setting the position you start a coroutine
in the coroutine you loop around a Lerp statement to move the position gradualy over time

fresh arrow
#

my bad i am already looking it up

languid spire
vagrant vault
# languid spire have you read the documentation?

some parts - i am not a programmer i try to use unity to my math project; in lot of uses they use this method in Updated i didn’t really see any others examples where somebody use it to staticky rotate

wintry quarry
vagrant vault
#

only example section

#

i will check it again

#

thanks

wintry quarry
#

You should look at what each parameter does

#

Because right now you're just kind of hardcoding certain things and it doens't make sense.

It's also unclear what your desired behavior is.

#

DO you want it to just snap to the end state? Or animate?

vagrant vault
#

actually snap, animation is less nesesery

this rotations are main thing that i will check so I don’t see reasons why not to hard code it

wintry quarry
#

Each with a different set of parts rotating around a different axis in a different direction

#

Right now you're hardcoding the center of rotation and axis of rotation

vagrant vault
#

yeah, that’s one method that rotate only columns up or down there is also one for rows and face(?) deep(?) don’t know how to name it

#

but what ever this code doesn’t really is importart

#

i changed yesterday this int degree to float degree

#

and doesn’t really help me :v

wintry quarry
#

there's no need to rewrite the code 3 times

#

And even for columns, you can't rotate around the same point all the time

#

Each column rotates around a different point

vagrant vault
#

as i told i am not really a programmer and don’t really want to be so code doesn’t really interest me as long as it works

wintry quarry
#

Understanding the code is really the best path towards getting it to work

astral falcon
naive pawn
#

that's 54 ways

#

there's an additional 27 ways if you allow opposite faces to rotate at the same time

wintry quarry
#

either way

#

my point is there are many ways

naive pawn
#

and an additional 36 ways if you allow opposite wide turns

wintry quarry
#

the actual number doesn't matter

#

(I was only considering quarter turns)

naive pawn
wintry quarry
#

not especially interested, thank you.

stuck palm
#

is there a way to intercept an alt f4?

stuck palm
stuck palm
#

awesome thanks

queen adder
#

I'm not sure if this is the right place to ask, but is wave function collapse usable on a non gridded world? I don't think there is a specific reason, but all the resources I've found have been for voxel or grid systems

#

if not, i'm pretty sure Graph rewriting would work, but that's a bit above my pay grade

verbal dome
#

Townscaper does it on an irregular grid

#

But still a grid

polar acorn
#

The only thing you really need is some definition of a "Unit" that you can replicate and place in a specific place.

#

This doesn't need to be grid, but a grid is the easiest to explain and simplest to implement

#

You might need to check more than one "Cell" in a direction if it's an irregular grid

queen adder
#

maybe I'm looking in the wrong place. I wanted to make a generation system that can create randomized rooftop shapes for a platforming game, but I wanted to ensure that all of the gaps are jumpable, regardless of the height difference between them. would it be better to instead use wfc to create sets of points that will be connected to create edges?

#

I might also be able to use a gaussian distribution to create the height difference, and then a probability distribution function scaled with height for the distance, to insure the gap is jumpable.

silver basin
#

How do I find an object in an array by using the Index?

languid spire
#

object = array[index];

queen adder
#

I wanted random generation with the only rule being that some point of the rooftops have to be anywhere inside the ballistic trajectory of the player from the previously generated roof

languid spire
#

so that is your starting point. Generate a random point within range and then generate the rest of the roof based upon that point

queen adder
languid spire
#

that is up to you, I dont know what kind of roofs you are trying to generate

queen adder
#

just roofs that aren't square, and are generally the same area, ish

languid spire
#

there are hundreds of forms of roofs

queen adder
#

flat roofs, specifically. sorry

west radish
#

implementing WFC isnt trivial, but I think all that really matters is that when you select a cell in the grid, youre able to find all the neighbouring cells. The grids shape mostly doesnt matter, an irregular grid just makes things a little more harder, I'm not sure how you'd actually store a grid like this one

queen adder
#

the issue is that It can't be a grid

languid spire
queen adder
#

so generate a map, then carve gaps along the cell walls

west radish
queen adder
#

or separate them by a random height, and then a random length given the height

west radish
#

all it does it move from one cell to a neighbouring cell, how those cells actually exist as your grid, isnt important to a WFC

queen adder
#

so can I use WFC to limit an inequality based on the shapes already generated?

spark knoll
#

Hey, so I wanna learn C# for unity and but I don't know where to start or how.
Can anyone guide me or something please?

eternal falconBOT
#

:teacher: Unity Learn ↗

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

slender nymph
silver basin
#

Why is this giving me these errors? here is the code:
if(takeCoverOrNot == 1)
{
navMeshAgent.SetDestination(chosenCoverPlace).transform.position); //this line is giving me the error
}

spark knoll
#

Come again please?

slender nymph
eternal falconBOT
slender nymph
silver basin
spark knoll
languid spire
slender nymph
spark knoll
#

Where was the pinner message in the channel again?

naive pawn
#

or press ctrl/cmd+p

spark knoll
#

So I have to use beginner scripting and then level up, right?

naive pawn
#

yeah, we all start there

spark knoll
#

awesome,
thanks!!

west radish
naive pawn
#

pretty much every modern app does

#

f1 and ctrl+/ are common "help" shortcuts, you should try them

west radish
#

only hotkey ive really used is ctrl +/-

#

its nice that you can zoom in and out

warm rune
#

Hi. Do you know how to create a globe in Unity and scale it to real size? Because I have a problem adding a texture to the globe because I have some limitations and when I want to drag the texture I get a red crossed out icon and I don't know where to change it to impose a texture on the circle and I would like to create a map like the SpaceX company from Elon Musk to track Falcon 9 rockets (only in the game Kerbal Space Program 1 on Steam). I would like this map to be original in the sense of authentic, different source code, etc. Thanks

swift crag
#

so your question is "how do I put a texture on a sphere"?

#

You can't drag a texture asset onto an object. You need to create a new material and use that texture in it

jagged hare
rocky canyon
#

u want a real world scaled earth in unity?

#

have fun w/ that

west radish
#

yeah, you really dont want to be dealing with a 1:1 scale version of an entire planet

rocky canyon
#

its a subdivided Cube.. stop the poles from having weird stretched textures

#

ur texture could look like this.. (having the bottom pole being where its cut from.. (but this is more #🔀┃art-asset-workflow just noticed the channel

#

anything > 1500 units is gonna start breaking

#

b/c of floating point precision errors/inaccuracies

rocky canyon
west radish
#

earths radius is about 6400meters wide. If you decided to place the center of the sphere at (0,0,0) then youre going to have to place all your other objects way off in the distance 6500 meters from the world origin. Trust me, you dont want to do that

swift crag
#

maybe more like 6,400 kilometers :p

#

But yes, you start running into precision issues when you get far enough away from the world origin

west radish
#

6400 only gets you on the surface

swift crag
#

I imagine that space games use higher-precision formats to store positions

#

and then position everything relative to the viewer, who stays at the origin

#

(That's basically what camera-relative rendering does..)

west radish
#

also any rigidbody at this scale is going to need some velocity like 7660 m/s thats what the ISS uses

rocky canyon
#

room gonna be getting warm this winter

west radish
#

im sure that KSP cheats in so many ways to make things easier

rocky canyon
#

ohh 1000 percent it cheats

#

pretty sure its sitting on some proprietary code too

west radish
#

id guess that because you cant do physics calculations once something is far away from (0,0,0), it wouldnt surprise me if when you go click on some ship out to the edge of the solar system, the game just offsets the position of everything to be close to origin

rocky canyon
#

thats pretty much a given.. Floating Origin System(s)

verbal dome
west radish
#

orbit calculations are dead simple too, those are basically just a circle. I honestly dont think youd actually need rigidbodies at all once you get into space

rocky canyon
#

^ this is what i use for my orbits

#

really good asset.. (nice and simple w/ gizmos to boot)

swift crag
#

shoot, you totally can

#

into the materials materials folder

spark sinew
#

orbits don't have to be circular, in general they are elliptic. with too much energy they become parabolic or hyperbolic

#

(in the last 2 cases that's not an orbit anymore)

verbal dome
west radish
#

ooh thats pretty

verbal dome
#

Even prettier when the generation process is animated :P

#

But yeah irregular grids are pretty cool for this kinda stuff

#

This geometry will be really useful for city layouts and such

swift crag
#

ooo

#

so each cell always has four neighbors

#

it's just all weebly-wobbly

#

(well, has at most four neighbors)

verbal dome
#

Triangles are present here - they just get split into quads when subdividing

swift crag
#

ah, I see

#

I am very interested in something like that for a Future Project

#

My dream is automatically generate suburban hell

#

which is particularly complex

verbal dome
#

I can always discuss this stuff so hit me up when the time comes

#

I just have a stack of effects like these that produce/modify some geometry

west radish
#

https://youtu.be/MwANWf6G9EE?t=123 I like what he does around this timecode, starting out with a fairly irregular triangle mesh with extra detail added into the colored regions

Here at Entagma we love to deal with yarns. This video extends the "yarn-effects" with a crochet approach. Using the delaunay triangulation of an input mesh and its dual diagram, the voronoi mesh, we build a procedural model that uses point color to blend smoothly between the two. That gives an intricate pattern, especially in the blending regio...

▶ Play video
#

I know its not so cut and dry to write a similar thing in Unity

verbal dome
#

Looks cool how the density changes

#

Houdini looks awesome. From what I can tell I am basically making a poor man's houdini in unity lol

#

For runtime tho!

west radish
#

Houdini is very nice

#

if only it was designed for runtime 😔

humble rain
#

hi guys, how much ram are you having for Unity ? I currently having 32 GB or ram right now so I don't know if i need more of it
ram used to be really expensive so i only can get that much

wintry quarry
humble rain
#

yes, ram got alot of cheaper right now i don't know why, it used to be like extremely expensive to get more than 32 GB. My air cooler is really huge so if I want to install more ram I have to remove it which is not ideal.

#

I want to work on persona 5 type of game

humble rain
#

i just hope i don't have to remove my pc air cooler

steep rose
#

you don't need all four slots taken up by ram, there are 2 stick kits in various sizes (i.e 2x 16gb or 2x 32gb)

#

32GB of ram is fine for most projects (I have 32GB and unity runs great)

humble rain
#

yes, but if i want install the ram kid, their air cooler fan..it too big and already shield everything 😭 I should go for an AIO water cooler but since my initial thought this would be a work pc, air cooler would be better, and I just pick the biggest air cooler

#

and now it just shield everything !!!

#

it's my first pc as well so I didn't know anything better

humble rain
#

since some technician he built this pc for me and I don't know how to remove the fan

steep rose
#

well your computer already has ram so you must have some clearance, so most relatively normal ram kits would work, although they probably wouldn't have fancy lighting as that may cause clearance issues as they would be a bit taller

#

also you can remove the cpu fan cooler via screwdriver and unscrewing its related screws

humble rain
#

i see, i thought we have to remove all the wired as well so i just panic

#

oh, if you saying to remove the cooler.. that's no no..

steep rose
#

well you would have to unplug the wire that is plugged into the motherboard, but it usually is not to hard

#

if you want it out of the case of course

swift crag
#

Time for a Dremel tool

#

💥

humble rain
#

well, if you already 32gb run great then there is not point worry about it for now. thank you.

swift crag
#

but yes, I've had a perfectly good time with 32 gigs of memory

steep rose
swift crag
#

(including going between multiple programs -- blender, substance painter, unity)

humble rain
#

i don't even know what is dual tower is when i purchase it

#

the fan it shield all the rams slots 😭

steep rose
#

All of your ram slots? if you are using normal ram then you should be able to upgrade it no biggie, if you are using low profile ram then 😬

#

do you know what your ram is?

humble rain
#

i am having this one.. it's indeed low profile..

humble rain
#

i don't even have the tools to remove all the screwdrivers

#

well, i will learn my lesson this time..

#

thank you you guys for your help

steep rose
#

yeah you should be able to upgrade to a higher ram value if needed, just make sure to compare the L W H of the new ram compared to your old ram so it doesn't have that bad of clearance issues. Right now your ram L H W (I'm guessing off of the my caliper measurements) is (133.35mm, 34.1mm 7.2mm (which is from the website )).

torn girder
#

!code

eternal falconBOT
west radish
#

2x32gb sticks

steep rose
#

he has 32gb total, so he has 2 16gb sticks

twilit merlin
#

void Reloader()
{
if (Input.GetKey(KeyCode.R) && m_LastTimeShot + AmmoReloadDelay < Time.time && m_CurrentAmmo < MaxAmmo){
// reloads weapon

           GetComponent<Animator>().SetTrigger("Reload");
            IsReloading = true;
            m_CurrentAmmo = MaxAmmo;
            GetComponent<Animator>().SetTrigger("ReloadDone");
            IsReloading = false;

        }
                     else {

                           }


    }

so basically it only will reload when the reload delay time elapses
is there a way for you to press the r key then the time passes then it does it
because now i have to keep mashing the key until the time elapses

#

i was told this belongs here

#

can you please elaborate on the input queue idea?

teal viper
twilit merlin
#

i did a bit of research and got it implemented

#

thank you for your trouble

royal arrow
#

I am making a puzzle game to learn Unity and am looking for a modern tutorial on how I should be setting up the level selection and scene switching systems. I'm making a puzzle platformer and am trying to keep the player and camera in a separate shared scene, loading levels additively on top of that. I have something implemented and working but it doesn't seem very maintainable long term so I want to refactor it now before things get out of hand.

I found a few tutorials but most of them focus on how to set up the UI, which is not what I'm actually interested in, and the rest use singletons which is a pattern I'm trying to avoid. If anyone knows of any videos or articles it would be greatly appreciated. Note: I'm new to Unity but not to programming in general so it doesn't have to be a "for absolute beginners" level tutorial.

rocky canyon
#

1 big persistent master scene

pure pike
#

how would i play an audio clip, like "GetComponent<AudioClip>()." idk what would go after the period to play it?

slender nymph
#

AudioClip is the asset. you use an AudioSource to play it

rocky canyon
pure pike
pure pike
slender nymph
#

!docs

eternal falconBOT
rocky canyon
#

"Unity AudioSource Play audio clip" or something

#

check out the example scripts as u learn..

#

good little things to try to remember

royal arrow
rocky canyon
royal arrow
#

Of course

rocky canyon
#

start a thread if u dont care

spark sinew
#

hi y'all, I am doing a project where i need to track road users (bikes, cars, pedestrians) in a scene and pass their position to a unity meta quest 3 app. How do I pass external data to a unity app so that it is nearly live ? I have never done this before

#

it is very little bit of data, just coordinates obtained from a python script

wintry quarry
spark sinew
#

ok

#

and on the unity side, is there something that can receive UDP data ?

wintry quarry
#

really nothing to do with Unity

#

you'd spin up a thread and make a UDP listener

#

Just... multithreading can be difficult if you have no experience with it, especially in Unity. You have to be very careful about how your UDP listener thread communicates with the main thread.

short fjord
#

can someone explain why my idle animation looks like this but my transition says it looks like this?

wintry quarry
#

I mean you're bringing up some very specific shader from some very specific video with not that many views from 2 years ago. It's unlikely anyone is familiar with this particular video let alone why it might work or not work. For all we know you copied the code wrong or the tuitorial never worked or something.

You're better off either:

  • Asking Daniel Ilett or his community
  • Sharing the details of the code etc... in #archived-shaders
unique moon
#

Sure, i will post the post in shaders tab

bright sequoia
#

I love how descriptive these definitions are 🧍

full kite
#

I got a question, maybe someone can help me cause I struggled to learn this thing. How does UI work and how to make an UI thats immune to any resolution. Like If I put something in the middle, I want it to remain there no matter what. Like Custom things cause If I wanted on the center or the edges I would anchor it.

#

Anchor it in a place and then move it with position does not help cause at different resolutions, it causes damage

delicate portal
#

Hey what does this error represent for me? I know the nullreference exception, just what about the eventsystem?

waxen adder
#

How do I set up my ide for unity? Had to make some major changes on my pc

#

nvm, think I'm figuring it out

charred spoke
#

!ide

eternal falconBOT
waxen adder
#

Looks like things are more or less working. Thoughts on Github copilot?

charred spoke
#

If you do not fully understand the code that the ai outputs then you better not use it. 9/10 times it’s gonna contain subtle bugs.

#

If it even compiles that is

burnt vapor
#

Something is null. I assume you can figure this out if you know the exception. Surely this happened recently so you know what code to look at?

#

Alternatively start logging and see when it happends

delicate portal
burnt vapor
#

But an interface is implemented by the user or internal code

#

So did you implement the method?

delicate portal
#

Yes, thats why I don't understand the error

burnt vapor
#

So what is the confusion exactly?

#

Either share the code in here, or start debugging

#

We don't know either

#

You assume a value exists, but it's null

#

Also, since this is a LogError the stacktrace is limited. We don't know if this is from your code or internal code now

#

If you suspect it's not your code, reload the project and try again

#

If the error persists, you did something wrong

delicate portal
#

In this environment registering interfaces works like this. I assume the is something to do with either the methods or the eventsystem.

waxen adder
#

Okay, so I have the ide set up, but intellisense is barely working. It won't look outside the class, so something like [CustomClass].[CustomFunction] won't receive any autocompletes. I also can't really use f12 on anything it seems, including monobehaviour. Any ideas?

pulsar trail
#

how can I load an image in asset folder into a sprite?
i've tried Resources.Load<Sprite>("filename") but it only works in Awake() or Start()
is there a way i can load a sprite in let's say Update()?

teal viper
teal viper
waxen adder
teal viper
pulsar trail
teal viper
teal viper
teal viper
waxen adder
teal viper
pulsar trail
waxen adder
teal viper
pulsar trail
#

alright thanks a lot

teal viper
waxen adder
#

Thanks for the assistance!

delicate portal
#

You can only load it in start

#

but thats just loading, not instantiating

#

You load it so its there and then you can get it by lets say


Sprite mySprite = Resources.Load<Sprite>("filename")
Image newImage = new Image();
newImage.sprite = mySprite```
burnt vapor
#

Something is null or not what you expect, test it

#

There's nothing we can do here, you have to check this yourself.

delicate portal
burnt vapor
#

Because it's an error log I assume

#

But like I said, you added code that triggered this I assume

#

If you really can't figure it out, make sure your code is saved and start stripping features until it disappears

delicate portal
#

The only thing that gives me errors are the Ipointer functions

errant glade
#

Hello
Do any one knew how to make Ml agent YAML file for Continuous and discrete action combine which work properly ?

burnt vapor
#

Tips have been given, not much else that can be done

delicate portal
burnt vapor
delicate portal
#

Yes I do.

burnt vapor
#

So share these methods

#

Also, what is RegisterInIl2CPP attribute?

delicate portal
#

[RegisterInIl2Cpp(typeof(IPointerUpHandler), typeof(IPointerDownHandler), typeof(IPointerEnterHandler), typeof(IPointerExitHandler))]
Thats how you register them

burnt vapor
delicate portal
#

Its not well documented

burnt vapor
#

Any reason why you'd do this compared to using the interface normally?

burnt vapor
#

99% of this conversation is guesswork

burnt vapor
delicate portal
#

In Unity, internally, you would use what you said.

burnt vapor
#

Why is it not an interface there? That's weird

#

I never used this so I'm not familiar with it

delicate portal
#

Yeah thats really weird for me as well, I didn't get use to modding unity games yet.

#

Because you have to compile them at runtime and its weird

burnt vapor
#

Is this supposed to be a mod to another game?

delicate portal
#

I mean it should probably be

naive pawn
#

is it not the unity one? that's documented as an interface

burnt vapor
#

This server doesn't allow modding third party games

delicate portal
#

Well then I apologise, I wanted to know the Unity side of it.

#

Maybe I was implementing an interface wrong, or so.

#

Thanks though, appreciate it, I'll figure it out.

burnt vapor
#

I have never seen this syntax, I was under the impression that these were the actual Unity interfaces

delicate portal
#

I don't get it why they aren't though

hollow slate
#

I've forgotten something pretty standard, and for some reason I can't find any concrete stuff online. I might be going crazy.
When you have UI elements, selecting them without using buttons and such would be to use a raycast, right?
Is this a 3D-raycast or a 2D-raycast?
Do I cast this in pixel-coordinates, as the UI is in that scale?
Does the raycast need to intercept with the UI?
Does the distance between the camera and UI matter when doing this?

delicate portal
hollow slate
#

Just finding the reference to them. It could be selecting them, sure.

delicate portal
hollow slate
#

This seems to be legacy though, is there no Unity 6 “recommended” solution?

#

I’m using the new input system

delicate portal
#

I rarely used that one

#

You can use it with it as well

#

But there is also EventSystem.currentSelectedGameObject

hollow slate
#

aha, I see. In this case it seems like I can use it.
I'm still curious though, as it might come up in my project quite soon;
How can I solve this without relying on my pointer specifically?

#

let's say I want to interact with the UI elements overlapping a certain object - instead of the pointer.

bitter apex
#

I'm trying to mess around with the fontsize of the text of a button whenever you hover over it, so it looks more interactive you know

#

I've got a bit of code that i believe would work, but I can't seem to drag the text of the button into the inspector thingy

#

the button uses text mesh pro

#

nevermind figured it out

#

docs is beautiful

delicate portal
hollow slate
#

anything. I want control over what UI element I interact with, regardless of where the value comes from

delicate portal
#

Can you give us an example of what UI are you building here? That can help

teal viper
#

Other than that, you could loop the rect transforms under the canvas and test if they intersect with certain bounds.

delicate portal
#

Yeah that works

spark knoll
#

So does anyone know State graphy in visual scripting?

#

I want a solution and I can't find any

#

basically the problem is , I am working at in a tower defense game and my character is working perfectly fine, but the thing is I want it to speed up after a 3-4 seconds and I am not able to find the proper node

#

I'm using Navmesh and Ai navigation for it I just want to speed up the walking speed so help me out please!

delicate portal
crude wagon
#

hey so i recently implemented a star for a 2d roguelike i’ve been working on and i can’t build now, i know it’s due to its use of using UnityEditor but i’m not sure how to get rid of it without breaking everything, i’ve toyed around with the configs for it and tried looking at forums and stuff but i just can’t find the solution. sorry if it’s a really easy fix i’m just pretty confused

delicate portal
#

A folder named Editor*

#

(as far as I'm concerned)

hexed terrace
#

without the *

delicate portal
#

That was for the correction

#

But yes

crude wagon
#

just the ones that interact with the editor or the full astra plugin?

hexed terrace
#

anything that has editor code in, so if it has using UnityEditor; it needs to be in an /Editor folder and not in a scene

delicate portal
crude wagon
#

alright perfect thank you guys !!

hexed terrace
#

sounds like you've put editor code in a class that is for gameplay though.. sooo.. this is probably gonna lead to other issues

umbral bough
#

Hi, I am trying to add a new camera and enable the post processing via script.
This is giving me a null ref, any clues as to why?

        private static void AddCamera()
        {
            // Create a new Game Object
            GameObject go = new("Camera");

            // Add the camera component
            go.AddComponent<Camera>();

            // Enable post-processing
            var ucd = go.GetComponent<UniversalAdditionalCameraData>();
            ucd.renderPostProcessing = true;

            // Add the audio listener to the camera
            go.AddComponent<AudioListener>();
        }
hexed terrace
#

which line is 342 ?

umbral bough
hexed terrace
#

There's no UniversalAdditionalCameraData component on it?

umbral bough
#

there is

#

this is an editor script, could that be the issue?

delicate portal
#

Try it out

umbral bough
#

huh?

delicate portal
#

Try putting it in an Editor folder

umbral bough
#

it is already there

hexed terrace
#

that's not.. relevant to the issue

#

you'll need to debug things out to see which thing is null - even those that should obviously not be null.

log:
go == null
ucd == null

umbral bough
#

should I explicitly add it?

hexed terrace
#

You already have it though, how does it become null?

umbral bough
#

well I create the camera within that same function, editor stuff is weird and sometimes requires refreshes/reloads and stuff

#

I added itt explicitly and that seems to have worked :/

verbal dome
#

@umbral bough Try waiting for a frame/until the end of frame before getting that component

#

At least with HDRP the additional camera/light components are not added instantly

verbal dome
coarse shore
#

can u collab with someone for free?

frosty hound
hexed terrace
eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

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

hexed terrace
toxic cloak
#

guys why am i getting lines between the platforms ```public class EnvironmentHandler : MonoBehaviour
{
public GameObject[] roadPrefabs;
public float zSpawn = 0f;
public float roadLength;
public int length;

void Start() {
    for (int i = 0; i < length; i++)
    {
        SpawnRoad(0);
    }
}

public void SpawnRoad(int roadIndex){
    Instantiate(roadPrefabs[roadIndex],transform.forward  * zSpawn,transform.rotation);
    zSpawn += roadLength;
}

}```

#

is it a visual bug or something else i cant figure out what m doing wrong sorry guys

winter aspen
#

if the origin is not exact, the road pieces may overlap slightly
same Y => y-fighting

#

a quick way to test it is to give the road pieces slightly different Y coordinates (like -0.05 to +0.05 instead of 0).
Try it out and see if the issue persists

#

this isn't the optimal solution, just a way to test what is happening

toxic cloak
naive pawn
#

if it is that, then making that section the same color should solve it

#

try checking the prefab and making sure the edges are uniformly black

winter aspen
naive pawn
#

though if it is that, then i don't think it disappear when near the camera/less steep angle

timber tide
#

alpha blending usually resolves fighting but then you got alpha geometry ;p

#

could also stencil the roads so they run with an incrementing buffer value

tulip nimbus
#

Is there a way for Destroy() to only destroy one GameObject and/or all of them or instances of that gameobject?

{
    Instantiate(particle, coin.transform.position, Quaternion.identity);
        Destroy(coin,0.1f); //Just destroy one random coin
}```
naive pawn
#

"instance of a gameobject" isn't really a thing

#

"instance of a prefab" is a thing, but i don't think that's tracked automatically

#

if you want to manipulate/manage/access them as a whole, you should just keep a list of gameobjects you've instantiated

#

destroying all of them would be looping through the list to destroy, then clearing the list

#

destroying a random one would be getting a random index, destroying the GO at that index, and then removing that index

stiff pollen
#

hello guys, I need a bit of help with implementing wall check

so I was following this tutorial and I want to implement the ( && !touchingDirections )but I had different code because his code has sprint while mine doesn't

#

this is mine

  
  { get 
       
      
      {
         
          return _isMoving; 
      } 
      
      private set
      
      {
          _isMoving = value;
          animator.SetBool(AnimationStrings.isMoving, value);
      } 
  }```
naive pawn
#

...ok, what exactly do you need help with?

stiff pollen
stiff pollen
stiff pollen
rich adder
stiff pollen
#

i need to implement the && !touchingDirections.isOnWall

#

it's a different code

burnt vapor
#

If you want to receive actual help, send the full code

stiff pollen
#

okay

burnt vapor
#

!code

eternal falconBOT