#💻┃code-beginner

1 messages · Page 525 of 1

strong wren
#

What does Debug.Log(rootObjects[7].activeInHierarchy); log in that Start method

rocky canyon
#

ahh gotcha gotcha.. 👍

delicate zinc
#

i just tried restarting unity to see if it was just being weird but its still doing it

strong wren
#

Double check with ``Debug.Log($"{rootObjects[7].name} {rootObjects[7].activeInHierarchy}");`

#

Though I suppose we should check the CamContainer too

delicate zinc
#

yea these are both true

strong wren
#

Debug.Log($"{rootObjects[7].transform.GetChild(0).name} {rootObjects[7].transform.GetChild(0).gameObject.activeInHierarchy}");

delicate zinc
#

still all true
sorry if this is annoying u btw

strong wren
#

Running out of ideas. You are running these from the Start method with the GameObject.Finds?

delicate zinc
#

yeah
at this point its probably just a bug or smt cos it should be working

#

ive tried tagging the objects to find them and using findgameobjectwithtag and it wasnt working either

stuck monolith
strong wren
#

@delicate zinc Can you send the current code and the full error you are getting

delicate zinc
burnt vapor
steep rose
delicate zinc
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

stuck monolith
steep rose
#

then ask your question in a correct channel, if it is about modding though, do not do it as we do not do that here

stuck monolith
steep rose
#

adding a script to a gameobject?

stuck monolith
#

I try 100 of times but still

polar acorn
#

Take a moment, formulate an entire coherent question in a single message, then ask it

steep rose
#

I do not know what that means, are you getting an error?

stuck monolith
steep rose
#

drag it onto the gameobject

stuck monolith
#

I try taht and I not have a script

steep rose
#

do you have a script made?

polar acorn
#

You have to make the script first

stuck monolith
#

No

#

Taht waht I need

polar acorn
#

Then make one

steep rose
#

go into the project window and rightclick -> create and make a new script

#

or you could make one in the inspector, nobody does that though lets be real here

burnt vapor
#

After you're done, !learn Unity

eternal falconBOT
#

:teacher: Unity Learn ↗

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

fading thunder
#

is Unity Learn the best place to start to learn Unity-relevant coding, or should I branch out to general C# tutorials on, let's say, udemy or codeacademy?

blissful yew
#
        {
            if (allUpgradesById.ContainsKey(upgrade.Id))
            {
                throw new Exception($"Duplicate upgrade Ids: {upgrade.name}");
                continue;
            }```
Does throwing your own exceptions break the program? I basically just a more attention grabbing Debug.Log
#

Or does it just continue along no problem

slender nymph
#

throwing an exception means that the method being executed halts there, which of course makes that continue; entirely pointless since it can't continue past that point

blissful yew
#

I like exceptions because they are easier to spott in the console. Is there a way to get that without halting anything?

slender nymph
#

Debug.LogError

slender nymph
#

or just use rich text tags to make your logs standout more (or both)

blissful yew
#

So what's even the point of throwing your own exceptions?

wintry quarry
#

Throwing exceptions is definitely not something to just do casually. It stops the entire control flow of the program

rocky canyon
#

rich text + ur own static logging class ftw

wintry quarry
blissful yew
wintry quarry
#

Or "could not connect to the multiplayer server"

rocky canyon
#

for me its so they stand out..

#

i can call Dbug.Green("ForExample"); or Dbug.Yellow.. and then its just rich-text in a regular Debug.Log

naive pawn
wintry quarry
#

Continue is redundant if there's no code that will run after it in the loop.

blissful yew
#

How much do you guys use exceptions?

wintry quarry
#

Rarely in game dev

naive pawn
#

not typically in game dev

wintry quarry
#

Depends what you mean by "use" though

blissful yew
#

yeah it doesn't seem useful unless things get very complex maybe

wintry quarry
#

I handle existing exceptions like file reading exceptions all the time for saved game systems

naive pawn
#

i don't have a ton of experience to back this up, but from what i do have, they're more relevant for longer, contained processes, like data processing

wintry quarry
#

Yes

naive pawn
#

they have their use cases

wintry quarry
#

Some languages don't have exceptions BTW. C and Go for example use a different approach.

naive pawn
#

and some interfaces use a similar approach to that with signaling return codes
Int.TryParse, the return value indicates whether it was valid or not instead of an error

#

or Physics.Raycast

#

or having both a successful value and error value be possible, like NaN from invalid floating point operations

#

these all encode "error" states without using exceptions

#

exceptions are more to control flow than just representing states, they have specific behavior like bubbling up

mild owl
#

Whenever i change the jumpPower Float the jump hight doesnt change could somebody tell me why

steep rose
languid spire
#

because you declared it as a local variable

polar acorn
mild owl
#

Oh thanks

queen adder
#

hi, is there anyone who could answer this: is it possible to make 2 certain scripts that both disable a certain gameobject without overriding one another. Im currently making 2 hiding spots for my game: a table and a locker, the locker seems to work perfectly fine and disables the player within the scene but the table doesnt seem to do so?

#

im pretty new to C# and unity in general so please go easy on me

#

i dont think im the only newbie in the chat here

polar acorn
queen adder
#

i was recommended to do everything into one file because i was pretty much repeating myself in the second script

queen adder
#

i actually havent come up with that 😭

#

i still need to learn a lot more about C#

polar acorn
#

You'd need one script that handles the object turning on/off, then however many other scripts you'd need for the different ways that script can be told to turn on or off

queen adder
#

but ill definetly keep your suggestions in the back of my mind

#

thank you!

queen adder
nocturne parcel
#

With the new input system, is it ok to verify player input in FixedUpdate?

#

I remember it wasn't ok with the old, but I guess this changed?

naive pawn
#

the press and release will be true for 1 frame each

#

you can check if it's currently being held in FixedUpdate like you could before

nocturne parcel
#

What about read value?

naive pawn
#

ah well same as checking if it's held

#

the values get updated per frame

cosmic dagger
naive pawn
#

(which will happen per frame)

nocturne parcel
#

ty

knotty arch
#

Hello. I have a projectile that I move by using rb.AddForce() which ForceMode is an Impulse. When I it collides with a wall, there is a chance where the projectile can spawn an enemy when destroyed. The problem is that before the projectiles is destroyed it continues moving after it collides with the wall, so the enemy spawns outside the room (this happens sometimes). The Rigidbody has continuous collision detection.

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

public class CheeseProyectile : MonoBehaviour
{
    public float speed;
    private Rigidbody2D rb;
    public Vector3 angle;
    public GameObject cheeseEnemy;
    public BoxCollider2D rataCollider;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        rb.AddForce(speed * angle, ForceMode2D.Impulse);
    }
    private void OnTriggerEnter2D(Collider2D col)
    {
        string colTag = col.gameObject.tag;
        if (colTag == "Player" || colTag == "Room")
        {
            if (colTag == "Player")
            {
                col.gameObject.GetComponent<NaachoHeartSystem>().Damage(1);
                Destroy(gameObject);
            }
            else if (Random.value < 0.2f)
            {
                GameObject queso = Instantiate(cheeseEnemy, transform.position, Quaternion.identity, transform.parent);
                EnemyEnabler enemyEnabler = queso.GetComponent<EnemyEnabler>();
                enemyEnabler.GetComponentsReferences();
                enemyEnabler.SetComponents(true);
                Physics2D.IgnoreCollision(queso.GetComponent<BoxCollider2D>(), rataCollider);
                Destroy(gameObject);
            }
            Destroy(gameObject);
        }
    }
}

wintry quarry
#

to prevent this you would either:

  • use a non-trigger and OnCollisionEnter2D
  • do your own manual CircleCasting or RayCasting in FixedUpdate to detect the collision instead of using a callback
#

Also there is no reason to have Destroy(gameObject); three times in your code

#

once is sufficient

knotty arch
buoyant schooner
#
private IEnumerator WaitToMine()
{
    Vector3Int tileTargettedPos = S_MiningControls.mouseCellPosition;
    Tilemap map = S_TileManager.tilemap;
    LiveTileData liveTileData = null;

    //whilst left mouse button still held down
    while (S_MiningControls.isMiningButtonDown)
    {
        //check if valid tile position
        if (liveTileData == null)
        {
            //find current pos of mouse to see if we get a new tile
            tileTargettedPos = S_MiningControls.mouseCellPosition;

            if (CheckIfValidTile(tileTargettedPos))
            {
                liveTileData = S_TileManager.liveTileData[tileTargettedPos];
            }
            yield return null;
            continue;
        }

        //check if our mouse moved
        if (tileTargettedPos != S_MiningControls.mouseCellPosition)
        {
            //mouse position changed

            //Set fade break sprite
            StartCoroutine(UntouchedTileTimer(tileTargettedPos));

            //set details
            tileTargettedPos = S_MiningControls.mouseCellPosition;
            liveTileData = null;
            continue;
        }
        
        //mine
        if(liveTileData.currentBreakTime >= liveTileData.maxBreakTime)
        {
            //break tile
            TileBase tileMined = map.GetTile(tileTargettedPos);
            AddMaterialToInventory(tileMined);
            map.SetTile(tileTargettedPos, null);

            //remove previous break sprite
            S_TileManager.DeleteBreakSprite(tileTargettedPos);

            //reset
            liveTileData.isAlive = false;
            liveTileData.currentBreakTime = 0;
            liveTileData = null;
            continue;
        }


#
        //BELOW THIS IS UPDATING STUFF, EVERYTHING IS IN ORDER

        //timer
        liveTileData.currentBreakTime += Time.deltaTime;

        //Debug.Log(liveTileData.currentBreakTime + " / " + liveTileData.maxBreakTime);


        //break sprite
        float percentageMined = (liveTileData.currentBreakTime / liveTileData.maxBreakTime) * 100;
        S_TileManager.SetBreakSprite(tileTargettedPos, percentageMined);
        liveTileData.TouchTile(); 

        yield return null;
    }

    if (CheckIfValidTile(tileTargettedPos))
    {
        StartCoroutine(UntouchedTileTimer(tileTargettedPos));
    }

    //nothing happened
    yield return null;
}```
#

Why is this Coroutine taking longer than 2 seconds? I've set liveTileData.maxBreakTime to be 2 seconds.

The code is a coroutine that happens when the player holds their mouse over a tile like in terraria and mines it. However, hovering and breaking the tile takes longer than expected.

Does this mean my code is making it slow?

Or have I got an error somewhere ?

buoyant schooner
#

Nvm! My Timing in real life is off lol

#

it just felt wayyy longer than 2 seconds

burnt skiff
#

hi guys i have this monobehavior script and im trying to link it to my object but its not allowing to drag and drop into it even though i have no compilation errors

eternal falconBOT
burnt skiff
teal viper
#

Read the bot messge

#

It appears as downloadable on mobile:

burnt skiff
#

its too long i need nitro

teal viper
#

Again, read the bot message. It tells you what to do with large code blocks.

burnt skiff
teal viper
burnt skiff
#

im trying to drag and drop this bt communication script onto another class with has this object

#

here

#

but its not allowing me to

teal viper
#

Take a screenshot of what you're actually dragging in

burnt skiff
teal viper
#

Ok, this is a script asset. You can't drag it in there. You can only drag instances of this script in there.

burnt skiff
#

oh so i need to put it in the scene first?

teal viper
#

Yes.

#

Or a prefab

burnt skiff
# teal viper Or a prefab

i managed to drag and drop the script now but its still saying my object reference is not set to an instance of an object

burnt skiff
#

this is the empty i linked the script to

#

here it got drag and dropped

teal viper
#

Ok, share the error details

#

!code
And take a screenshot of the error first

eternal falconBOT
burnt skiff
#

on line 56

#

i want to use my method on the object

#

but it says this

teal viper
#

Ah, nevermind that. It's a difference variable

burnt skiff
#

yea

teal viper
#

This looks weird. I've never seen a syntax like that. What are you trying to do here?
drone => drone.ID

burnt skiff
#

its a key selector used to specify that i want to create the binary tree by the drone's ID

#

my drone has many attributes and i want to create the binary tree based on its ID

teal viper
#

Is that a lambda expression?🤔

burnt skiff
#

yea

teal viper
#

Select the error and take a screenshot of the whole console

burnt skiff
teal viper
#

I see. So that's when the lambda is invoked. drone is likely being null there.

burnt skiff
#

oh alright maybe i need to change it to agent

#

still the same

teal viper
#

It's likely a value provided by the tree, so changing the name of the variable wouldn't really do anything

burnt skiff
#

this is the drone code

teal viper
#

The drone code is unrelated. The value is provided from DroneBTCommunication

burnt skiff
#

oh alright

teal viper
#

I feel like you don't understand how your own code works, do you?

toxic yacht
#

at line 32 in DroneBTCommunication what is the behavior you want if drone is null? or should drone ever be null?

#
int nodeKey = keySelector(node.drone); // node.drone is null
drone => drone.ID // results in null ref for drone passed to lambda at line 56 in Flock
#

just like dlich said

burnt skiff
burnt skiff
#

oh wait

#

nvm

#

before i applied the method onto the object i partitioned the drones based on a pivot and stored them into arrays, this method works fine but how does it suddenly become null

#

once i remove line 56 the code works fine so the lessthanorequal array does exist and it contains my drone objects inside it

teal viper
#

It feels really weird to me that you're using pretty complex syntax(that a beginner wouldn't know how to use), yet have difficulties debugging a null reference error.

toxic yacht
#

i think I see what's happening

#

nevermind I was looking at the insertion and though the root assignment was messed up. one of the drones in the drone array must be null. I'd suggest moving the lessIndex++ out of the array access. ik in C that's supposed to happen after operations but that's making my spidey sense tingle.

#

my feeling is that the root node's drone is being assigned to null (a.k.a. drones[0] is null), so when the second node insertion is done, the KeySelector call on line 32 results in the null ref.

#

the call stack for the error always being at the root node despite drones being generated randomly makes me think this is a one off error, and the only place I think of a one off error happening is in partition drones.

burnt skiff
#

i printed all of the values inside the partition array and i cant find any drones that could be null

radiant glen
#

Trying to make the health save from level to level, having the current health save as a int when the end point is reached, which I will then put in Player Prefs, I keep getting this error though

eternal falconBOT
wintry quarry
#

But it's pretty clear you never assigned instance

#

your code makes no attempt to do so
so you're getting a very typical NRE

toxic yacht
radiant glen
#

Okay, how do I assign an instance? and what is a NRE?

wintry quarry
wintry quarry
#

@radiant glen see you are trying to access this Health.instance variable. Since that variable is null, you get an error. You cannot access a null reference or you get a NullReferenceException.

It is null because you never assigned it. You assign variables in C# with =

radiant glen
#

Okay, I see, so what do I need to assign then?

wintry quarry
#

The variable

#

It seems like you're trying to do the singleton pattern

#

but you did not fully implement it

#

typically you would do something like this:

void Awake() {
  instance = this;
}``` in the `Health` script
#

See how you can assign a variable with =

radiant glen
#

Oh! Okay that makes sense I see

#

Perfect that worked thank you!

teal viper
# burnt skiff

Instead of logging, I'd try to step through the code with a debugger, when the drone is being null. It should be a matter of seconds/minutes to figure out where the null is coming from.

burnt skiff
burnt skiff
#

it seems that the error is due to the root being null

#

because when i add a debug log to check if root is null before adding nodes it appears root is null and when i put it after the program just stops

#

so im guessing that's where the problem is

toxic yacht
#

the root starts off as null, but is assigned with line 29 in DroneBTCommunication. However, the root's drone is null, which causes the error. The only way I can see the root's drone being null is if the first drone in the drones array is null. but if everything in the drones array is assigned then that's a headscratcher.

burnt skiff
#

yea i figured out the error it was because when i was creating the node i didnt specify it to the drones inside the array it just used the local variable drones which is null, i fixed it by just adding this.drone

#

thank you guys for the help

toxic yacht
#

they fooled us all lol

queen adder
#
    public LayerMask boxLayer;
    public GameObject currentBox;
    public Collider2D myCollider;


private void OnTriggerEnter2D(Collider2D other) {

    Debug.Log("Something found");
   if (other.gameObject.layer == boxLayer) {
        Debug.Log("FoundBox");
        currentBox = other.gameObject;
    }
}

What do i miss here. The Layer in the BoxObject itself and the Layer in the boxLayer varible are correct, but it only prints "Something Found"

faint agate
#

my porblem is player vertical camera jitter lag when falling. I fixed it by turning interpolate to none on my rigidbody but then it made my game feel horrible and the bullets are super laggy now. Is there anything else I can do to fix the jitter lag when falling without turning off interpolate ?
I can send my player movement or camera script

languid spire
queen adder
#
if (Bla == x or y) 
if (Bla == x || x)

What is the right sytax for that? if condition == Option 1 or Option 2. Is that even possible in c# ?

#
if (lastPositionPoint.transform.position == (new Vector3(1f,0f,0f)+transform.position || new Vector3(-1f,0f,0f)+transform.position))
charred spoke
#

if(Bla == x || Bla ==y)

ivory bobcat
umbral bough
#

Hi, I've been losing my mind with this one since yesterday 😭
So basically, C# implementation of a file watcher is awful(and that's an understatement), and for some reason, gets triggered mutliple times when a file changes, and even detects incorrect events.
None of that would matter to me, I just need it to trigger when the file is changed, renamed or deleted, which it sort of does, but multiple times.
Issue is, when it triggers multiple times, and I am guessing here, it cancels the execution of a method it previously called?????
Trust me, I am as confused as you are probably.
I used rider to try and debug, it basically kept jumping all over the place 🤦‍♂️
So finally, I decided to see if it's me being majorly incompetent, and to my surprise, I wasn't.
Calling the exact same function the file change event calls results in flawless behavior and the expected result.
And due to debug logs I placed all throughout code, I was able to determine that execution of functions literally gets cancelled by another event trigger or something, I am losing my mind at this point.
I would really appreciate someone helping me debug this one 🥺
Here's the script responsible for dealing with config logic.
Lines of significance are:
9 - Calling the function on a keypress that assured me my logic worked just fine
110 - FSW setup and the function I am calling
137 - Function that stops midway through when called by a fsw, but works fine otherwise

burnt vapor
#

Probably doesn't even work in current Unity

burnt vapor
#

Something like that

#

It might also be Vector3.forward

burnt skiff
#

hi guys i have an object for controlling my UI but for some reason even after i link it to to the textinputfield and the button it dosent work

#

i cant use the input field or press the button

languid spire
burnt skiff
languid spire
#

Add some logging

burnt skiff
languid spire
#

screenshot your heirarchy

burnt skiff
languid spire
#

you do not have an EventSystem

burnt skiff
languid spire
#

no, just add one to your scene

burnt skiff
#

omg it works now tqqq

languid spire
#

it would have been created when you added the Canvas, you must have deleted it

burnt skiff
#

ohh alright mb thanks again

eager spindle
eager spindle
astral falcon
eager spindle
burnt vapor
astral falcon
languid spire
languid spire
queen adder
#

Has anyone knowledge about with DotTween. I look up Stack Overflow, but in my code is still a syntax error

#
 transform.DOScale(new Vector3(0,0,0) ,1f).onComplete(() => Destroy(gameObject,0.1f));
naive pawn
#

it's a field, don't you need to assign to that

umbral bough
#

just a wild guess, onComplete() is an action and you gotta do onComplete => Destroy(gameObject, 0.1f); instead

naive pawn
queen adder
#

Still a syntax error

umbral bough
naive pawn
#

but also that's not how you set an action

#

like i said, you need to assign to it

#

onComplete = () => Destroy(...);

umbral bough
#

my bad, I am tired, you should do what that guy suggested

naive pawn
queen adder
#

That worked

hexed terrace
#

You want to use .OnComplete() not .onComplete()

#

IIRC

naive pawn
#

a syntax error means c# can't read your code at all
what you had before was a semantic issue; it sees what you're trying to do but it's invalid

naive pawn
#

actually seems like it just sets onComplete. so not sure what the benefit over the assignment is if it has the same behavior thonk

hexed terrace
naive pawn
#

OnComplete seems to be documented, at least..?

hexed terrace
#

DOTween lets you string a load of things together, so you want the () to be able to add another extension

queen adder
#
transform.DOScale(new Vector3(0,0,0) ,1f).OnComplete(() => Destroy(gameObject));
``` This works, thank you for your help
naive pawn
#

why's onComplete accessible though thonk

hexed terrace
#

You can also just do

kindred spade
#

hey there! i'm following a tutorial on how to make a flappy bird game for my first project just i can't seem to figure out why the code doesn't work here is my code:
the problem is that for some reason when i touch the trigger it doesnt move my score up!

hexed terrace
#

do you get the 'addc' log in the console?

#

any errors?

#

what debugging have you done?

burnt vapor
#

Not just for readability

#

Stuff like events need a proper method reference and not a lambda if you want to unsubscribe, so get used to this instead

kindred spade
#

im pretty sure that my addscore code works because i added score with a contextmenu

hexed terrace
#

so your physics isn't setup correctly (colliders/ rigidbody/ etc) - go back through the tutorial where it tells you about adding this stuff and see what you missed

kindred spade
#

ahhhh

hexed terrace
#

If 'addc' isn't being printed to console, OnTriggerEnter2D isn't being called.

kindred spade
#

ii have my sprite set to rigidbody 2d and my trigger to box collider

#

aha

hexed terrace
#

Your sprite isn't "set to rigidbody"

Your player GameObject has a rigidbody component added

kindred spade
#

my bad i don't know how to call everything yet xP

#

my sprite has a rigidbody 2d for gravity and box collider 2d to collide and my pipe has a box collider 2d i don't get what i've done wrong i already checked the tutorial a vew times because i thought i did this wrong

languid spire
#

show the inspectors of both objects

kindred spade
#

this one is for the trigger

#

this one is for the sprite

languid spire
kindred spade
#

oh lord

#

im a dumdum

#

tank you

#

that explains it

#

it works thanks so much!

languid spire
hexed terrace
#

but also, don't get hung up when you do make small mistakes - we all do it

kindred spade
#

i don't know if i'll become a dev i'm far far away from that i'm just trying to learn something instead of scrolling youtube all day haha

languid spire
upbeat snow
#

hi guys, I currently have a script in a GameManager gameobject that calls a function whenever a value is added to a score. How can i detect whenever the function is called so that my ScoreUI (which is another gameobject) could call an animation? tysm

upbeat snow
cosmic dagger
upbeat snow
#

tyty

twilit rivet
#

nvm

crimson widget
#

Hey, how do I set a splines end point position through c#? I am trying to move and update how a spline is shaped at runtime, but I cant find the correct method or whatever

astral falcon
upbeat snow
#

hi guys, here I have script "points" attached to an event in which triggers the "triggerAnimation" function when called; however the animation seem to only play the first time the event is called and it doesn't work afterwards. The console message does continue to show up tho, anyone know what the possible problem would be? animator also provided here if it helps tyty

astral falcon
upbeat snow
#

and when i turn it off it's the situation i mentioned earlier :/

astral falcon
polar acorn
#

If you don't loop it, it'll play once when you enter the state and then be there forever

queen adder
#

Sorry i have a very basic Question, how to accesse indivual Compontes in a good/professional way? Even then they don't have a Script attached. What i used to far ```cs

// Option 1
private TextMeshPro moneyText;

private void Awake() {
    moneyText = GameObject.FindGameObjectWithTag("MoneyText").GetComponent<TextMeshPro>();

}

//Option 2
public GameObject moneyTextObject; // Drag and drop Gameobject with editor
private TextMeshPro moneyText;

private void Awake() {
    moneyText = moneyTextObject.GetComponent<TextMeshPro>();
polar acorn
wintry quarry
#

and you're done

polar acorn
#

And the correct way is to just make moneyText public and drag it in and have no code at all

wintry quarry
#

And option 4, which is really the most "professional" way generally:

[SerializeField] private TextMeshPro _moneyText;```
queen adder
#

But i can't drag the Gameobject from the hierarchy into this public Field (i think i't because, the is a Componet of a GameObject)

wintry quarry
#

not a TextMeshPro

polar acorn
wintry quarry
#

You should, in the future, just use TMP_Text instead of either of those

#

it works for both

queen adder
wintry quarry
#

no

queen adder
frank zodiac
#
using UnityEngine;

public class World : MonoBehaviour
{
    [SerializeField] private int _width = 10;
    [SerializeField] private int _height = 10;

    private Tile[,] _tiles;

    private void Awake()
    {
        _tiles = new Tile[_width, _height];
    }

    private void Start()
    {
        for (int x = 0; x < _width; x++)
        {
            for (int y = 0; y < _height; y++)
            {
                GameObject tile = new GameObject();
                tile.name = $"Tile ({x}, {y})";
                tile.transform.position = new Vector2(x, y);
                tile.AddComponent<Tile>();
                tile.AddComponent<SpriteRenderer>();
            }
        }
    }
}

is there a less performance-intensive way to instantiate a large number of gameobjects?

rich adder
frank zodiac
#

Like in terms of performance

rich adder
#

try it and see, not likely anything substantial
Idk if Instantiate is better than New GameObject

#

cloning vs actual new() 🤷‍♂️

timber tide
#

wtf constructing a whole new gameobject

obsidian mesa
#

Hello, a question, if I pass my code here, could you tell me what the error is about my character not jumping?

cosmic dagger
#

doing new GameObject() is worse because you have to manually add all the necessary components instead of using a prefab with everything all set up . . .

night raptor
obsidian mesa
#

It tells me I can't upload the code

cosmic dagger
eternal falconBOT
obsidian mesa
#

finaly

#

well, the error is that he does not jump, the character detects the ground and the jump key but does not jump, I checked the jump force, gabedad and mass but even changing those parameters he does not want to jump

rich adder
#

you skipped that part

#

also I dont see anywhere if you are debugging enSuelo value
Debug.Log("¿En suelo?: " + enSuelo);
what is the value here when you try jump ?

#

you should not have one Frame events such as KeyDown in PhysicsUpdate / FixedUpdate

obsidian mesa
timber tide
#

chatgpt gone incognito

rich adder
#

we are not using rocket science terms

ripe matrix
#

Hey, i have this error where i cannot make a reference to the camera fro some reason. Does anyone know why?

rich adder
languid spire
ripe matrix
rich adder
#

one of the object is scene and other is prefab?

verbal dome
#

I doubt its their own class, it has camera icon

rich adder
#

you cannot drag Scene objects in the Prefab

ripe matrix
#

Is there another way to reference it?

rich adder
#

pass the reference on spawn

ripe matrix
#

How do i do that?

ripe matrix
#

Ok, thanks!

rich adder
#

with camera you probably get away with Camera.main property but this is probably better to learn properly from link above for other objects too

frail hawk
#

you can also keep the reference on the script that instantiates and after instatiating just add the reference to the prefab

rich adder
#

yes thats what the link i sent suggests you do

frail hawk
#

oh yeah, i see it now, it is the cleanient soloution

rich adder
#

yeah its a simple form of DI (dependency injection), very handy for other things too

frail hawk
#

direct injection

#

oh yeah

#

i think unity should provide an easier solution, people ask this thing alot.

#

in fact one of the most asked questions

#

mayn people start to do foolish things such as Find

rich adder
#

I rather like the DI that .net apps have, idk games are a bit different

#

they do have things like ZenJect (third party though)

dry jungle
#

Hi in my game i can't look up, does someone knows how to fix it?

steep rose
#

look at the clamp

#

also you should use the floats you made for the clamp

rich adder
#

thats why you set the sensitivity so high

#

mouse inputs are already framerate - independent

#

also your clamp is wrong , doing 90 90 when it should be -90/90

#

if you have top and bottom clamp variables, but why aren't you using them

rancid tinsel
#

if I'm running an if (audioSource.isPlaying == false) every frame but the audio source is set to loop, would that ever go through? is there a frame or moment between the loops where that is set to false or is that not something i need to worry about

rich adder
#

wouldn't it just be easier to test this lol

timber tide
#

You only need to set it false once if that's what you're asking

rancid tinsel
rancid tinsel
rich adder
#

if its just loop its probably still isPlaying until you call Stop() but dont take my word for it

rancid tinsel
timber tide
#

audio looping isn't something independent. If the streamer isn't playing then the audio cannot play thus cannot loop

rancid tinsel
#

or is there a different reason

rich adder
#

I would just test it and make sure it works how you expect in your specific use case

dry jungle
#

Does anyone know how do I fix this error?

rich adder
polar acorn
#

What error

dry jungle
polar acorn
slender nymph
dry jungle
#

Ok

slender nymph
#

yes but the warning you are looking at is not the error. configure your IDE

polar acorn
#

You haven't shown any

steep rose
#

open your console

dry jungle
#

oh

steep rose
#

show us the error

dry jungle
polar acorn
# dry jungle

So, that first one is an error. Which would be underlined if you configured your !ide

eternal falconBOT
polar acorn
#

So do that, fix the thing that's glowing red, then try it

slender nymph
#

this is non-negotiable. you have to configure it if you want to get help here.

steep rose
dry jungle
#

I can't find Editor Attaching

slender nymph
#

please read the instructions a bit more carefully

dry jungle
#

I'm a 2019 Visual Studio user

slender nymph
#

your point being?

dry jungle
#

Using 2019 Visual studio

slender nymph
#

do you think that Unity 2019 in the instructions you should be following is referring to Visual Studio 2019?

#

okay? wow they deleted their message, likely after realizing what i was trying to convey to them

prisma thicket
dry jungle
#

I can't find IDE

slender nymph
#

wdym you can't find IDE? your ide is visual studio

dry jungle
#

Common7 Then

slender nymph
#

why are you looking for that? you already had visual studio selected in the dropdown according to the screenshot you posted then deleted

polar acorn
fickle plume
dry jungle
#

I'm dumb

steep rose
dry jungle
#

ok

prisma thicket
slender nymph
fickle plume
# eternal falcon

@dry jungle Should install 2022 from the Hub as in instructions there. It's faster and it will be properly setup out of the box. Will just have to switch to it in preferences.

slender nymph
#

if you want to raycast from the mouse then you need to use the camera to create a ray from the mouse's position and use that

prisma thicket
slender nymph
#

(it is)

prisma thicket
#

i hate myself

dry jungle
#

I did it

opaque cairn
#

i would love some help if anyone had some tips to give.
i've been trying to get a code up and running for a 3d platformer practice game, etc. But i'm having the worst kind of trouble with the rigidbody physics, and find my dude sliding all across the place on inclines, and i have no idea why it's happening. it's not even downslops, that could be debatably useful, but i'll slide horizontally off a ledge or something it's slightly inclined or enclosed by walls. i don't really understand why.

languid spire
#

Please do not post screenshots of !code unless requested to do so

eternal falconBOT
rancid tinsel
#

can you have multiple scripts on 1 object calling DDOL or should you split them up?

prisma thicket
prisma thicket
#

ok so i tried it and when i right click on tree nothing is happening

dry jungle
#

It's still there

slender nymph
fickle plume
mild owl
#

why isn't the particle playing when i jump i've been trying to figure it out for the last 30 minutes even asked chat gpt but i might just be stupid

https://hatebin.com/hotqaytjnk

prisma thicket
rancid tinsel
opaque cairn
slender nymph
slender nymph
mild owl
prisma thicket
#

oh the interact range i have set to 20 and the camera angle is like this

fickle plume
eternal falconBOT
#

:teacher: Unity Learn ↗

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

prisma thicket
#

its an isometric camera

slender nymph
steep rose
#

the correct keycodes

dry jungle
#

BYE

prisma thicket
slender nymph
#

well you're drawing the raycast, does it appear to be long enough to reach the tree? also is the tree's collider convex?

steep rose
slender nymph
#

they came here for answers, not to read /s

steep rose
#

that is an answer 🤷‍♂️

stuck palm
#

How can i rotate this sphere along the local red line?

prisma thicket
slender nymph
steep rose
slender nymph
prisma thicket
slender nymph
#

no, you are drawing a red line to represent the raycast. do you just not even know your own code?

slender nymph
#

let me guess, it's AI generated and you felt that wasn't important to disclose?

slender nymph
#

well then if it isn't ai generated then you wrote the code and you wrote the comment that literally says "visualize the ray"

prisma thicket
gleaming kraken
#

how unoptimized is this code? I'm aware it's very, very messy. But in terms of performance, is it as bad?

opaque cairn
#

That's everything. And I am learning through the tutorials, but I've come across through experimentation and wanted to know if it was salvageable.

slender nymph
slender nymph
hexed terrace
gleaming kraken
gleaming kraken
slender nymph
#

it's literally just storing it in a variable

timber tide
#

usually the IDE asks if you want to use the nonalloc version

gleaming kraken
languid spire
hexed terrace
#

that's what caching is

slender nymph
# gleaming kraken really? That's it?

yes, instead of calling GetComponent a bunch of times for the same component, call it once and store it in a variable and reuse that variable in each place you were initially calling GetComponent for that type

fickle plume
opaque cairn
#

hmm. well i have it so that when airborn the physics material switches to a frictionless version.

#

i've attached a more grounded material as well for the isgrounded state, but that didn't make any changes so i didn't commit to it.

gleaming kraken
opaque cairn
#

i'll give those tutorials a look t hough

slender nymph
gleaming kraken
fickle plume
opaque cairn
#

mass might be one of those elements. I haven't really messed with anything mass i don't think.

stuck palm
#

doesn't seem to work for me. looks like it still rotates along its global axis

slender nymph
#

just use transform.Rotate

stuck palm
#

okay, thanks

graceful walrus
#

I am developing something very similar to this, https://pin.it/3kI90Vm07, but I have a concern. In my game the player can use multiple guns, all which could have different height size. When shooting, I want the bullets to move only in the y-plane towards the direction of the mouse. The problem is that the if the bullets come out of the muzzle of the gun, since the position of the muzzle of each gun can be in a different y-position, it makes the bullets not travel parallel to the shooting y-plane. This is because the gun is position so that its handle is set to an offset relative to the player's position. This makes the shooting in my game to not be consistent. How can I avoid this? Am I thinking in the wrong way?

wintry quarry
#

to avoid such a problem

#

Sometimes there's a particle effect that happens at the same time that appears to come from the gun itself

#

but it's an illusion

#

Sorry i just looked at the link and saw it's a topdown lol.

Similar things apply though

#

Are they all raycasts? Or are there slow moving projectiles?

graceful walrus
rich adder
#

You probably want to raycast on a plane unless you need the y to go up and down

#

even without one , if you're using mouse as target direction you can just keep the Y pos the same height as your weapon/player/firepoint

#

like mousePosTarget.y = firepont.y , or something. Then calculate the dir

wintry quarry
# graceful walrus They are raycasts

Then just do the raycast always from the same place. The visual projectiles (line renderers, particles, etc) can come from the gun muzzle to the place the raycast hit

flat tide
#

Hey! I have a quick question how can I make a patrolling NPC hold a spot for a few seconds maybe add a animation before moving to the next waypoint?

rich adder
flat tide
#

So i can base mine on that

rich adder
#

ofc its an example, you can always make it randomize time and other stuff, a lot of Coroutine exmaples show the WaitForSeconds class but I personally don't like using it so i just manually do the timer as shown above
btw you can also use Update and use Time.time instead

graceful walrus
rich adder
#

or don't rotate the X on the firepoint if you're doing that

#

you'd have to show more details of setup currently to have more specific

graceful walrus
rich adder
graceful walrus
#

Assuming the bullets come from the muzzle of the gun?

rich adder
graceful walrus
rich adder
#

rb.velocity = dir * speed

graceful walrus
rich adder
graceful walrus
# rich adder sorry lol maybe show the current code and setup + whats happening right now, cou...

I don't have the code for it just yet, it is just my analysis of the example I showed initially. In that example, their is only one weapon that is aligned with the shooting plane, but if the player was able to use multiple gun's and some of this gun's are bigger(for example, a rifle compared to a pistol), it would mean that the muzzle of the gun is higher and so the player would be shooting at a height depending of the gun's size, which it's not what I want

visual bison
#

Hi, you've all probably have heard this a lot, but I'm new to Unity and am just completely new to any kind of programming software. Do you guys have any suggestions as to how to get started in learning how to use Unity and learning how to program? I appreciate any kind of advice! I'm completely new, so I don't know anything. Even a video tutorial that you think is very helpful will be much appreciated.

slender nymph
#

there are beginner c# courses pinned in this channel and the pathways on the unity !learn site are a good place to learn how to use the engine

eternal falconBOT
#

:teacher: Unity Learn ↗

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

prime hinge
#

hello every one i have an array of 6 buttons
and i want to change the position of each one
each time we press one of them but for some reason it show me that i didn't assigne any variables to my buttonsE array

#

the problem

rich adder
slender nymph
eternal falconBOT
silk night
#

Please post code that long to a link above

#

nah

#

Well you should debug or log your conditions for jumping

#

figure out which of them is not true while it should be

#

Yes, but you can still modify it?

slender nymph
#

and yet you should still log the relevant info instead of assuming other people will magically fix it for you without that useful information

silk night
#

well, guess theres no helping you then

#

its clearly not working code

#

lmao

#

i have, game dev to be precise 😄

rich adder
#

if you think gpt is more useful than anyone here , you are sadly mistaken little bro

silk night
#

wrong layer on the floor?

#

alright, <@&502884371011731486>

#

not gonna be insulted here

rich adder
#

no reason to be an ass towards other people <@&502884371011731486>

#

little bro the mods/admins can view deleted comments , so whatever.

#

they havent insulted you so there was no reason to do it

silk night
#

i told you to debug the code and you responded with "i wont do that", how are we supposed to help you then?

frosty hound
#

That's not how this works. Play nice.

#

Also this kind of attitude is not welcome here. You're in the wrong server otherwise.

#

!mute 1278821301619921048 1w Ok

eternal falconBOT
#

dynoSuccess whitefoomusic was muted.

queen adder
#

🍿

#

anyways, have anyone tried transfering a 2021 project to unity6?

north kiln
#

Bizarre

#

They are the same version so sure

rich adder
#

oh in that case 2021 should be just fine, depends what types of assets ofc but should be non-issue

north kiln
#

2021, what an edit

queen adder
rich adder
#

2 year gap UnityChanLOL

silk night
queen adder
#

but I have different projects on different versions, soo-

rich adder
#

as long as you got VC test away!

north kiln
#

Yes, we upgraded, yes, there were numerous things that needed fixing

#

Our URP custom shaders broke too

silk night
#

lmao

rich adder
#

the most "breaking" change for me was all my Rigidbodies had to be switched from velocity to linearvelocity

silk night
#

he coming back for more

rich adder
queen adder
#

I would have wanted to read this from start, but I just woke up lol

north kiln
#

!ban 1278821301619921048 30 come back in 30 days when you've decided to be less of a fuckwit

eternal falconBOT
#

dynoSuccess whitefoomusic was banned.

north kiln
#

Our custom shaders broke because the way keywords are resolved changed

#

We had to declare every keyword we were using in hlsl files at the root of every shader graph

silk night
#

i wish i could write non-shadergraph shaders 😐 another dev had to fix that stuff in the project

queen adder
#

hmm wont you have to redo the shadergraphs?

silk night
#

nah shadergraphs are mostly fine as the nodes update too

queen adder
#

or were you using hlsl? (I suck at both so probably not good idea to do all that myself)

north kiln
#

If you're not using custom lighting then you probably won't have an issue

polar acorn
#

Dang I had a meeting and I missed some popcorn

vocal lake
#

Hey, I'm extremely new to Unity and C#. Could anyone help me with collision detection code for a prototype I'm working on? I think it should be really simple but I can't get it to detect the collision that makes the object play a sound.

slender nymph
#

!ask

eternal falconBOT
slender nymph
#

(pay particular attention to that last part)

rich adder
vocal lake
#

Thanks!

steep rose
#

I guess he really didn't want to debug

blissful yew
#

How are you supposed to test a clean save on mobile? It always fetches the previous save data on the phone, and there's no way to clear it out as far as I can tell? My game doesn't have a save slot system or 'new game' option

#

I tried to use PlayerPref to detect if it's the first time the game has been launched, and clear save data if so, but that only works one time and then it doesn't even work for subsequent builds

slender nymph
#

if you're saving data using playerprefs and want to clear all of the saved data, just make a button that calls PlayerPrefs.DeleteAll

blissful yew
#

Sure but I only want to do that the first time the game is played, and I don't know how to do that

slender nymph
#

well if it's the first time the game is played, then there won't be any saved keys

blissful yew
#

Well I just deleted the game on my phone and rebuilt it and the added playerpref ('GamePlayedBefore') was found.

#
        {
            Debug.Log("First Time Opened");
            PlayerPrefs.SetInt("FirstTimeOpened", 1);
            PlayerPrefs.Save();
            
            if (Directory.Exists(_playerDataDirectory))
            {
                foreach (var file in Directory.GetFiles(_playerDataDirectory)) File.Delete(file);
                Directory.Delete(_playerDataDirectory);
            }
            FindObjectOfType<LevelManager>(true).ResetAllLevelData();
        }
        else Debug.Log("Has Been Opened Before");```
slender nymph
#

well that's because it's not the first time it's being played. you already saved data. if you want to clear it out for testing, then just make a button that does that

blissful yew
#

yeah that's annoying to have to shoehorn a button in but ok

slender nymph
#

it's either that or you have to do more work by saving the current version number and making sure to increment that version number each time you want to clear it, and also make sure that code is removed for release so you don't fuck over your players for each update. plus having a button would allow your players to delete their own data if they so desired

blissful yew
#

done lol

woven otter
#

Hello,

I have a little problem with camera + rigidbody fluidity. I used to use a character controller, but I decided to change it to have a physical interaction with some objects.

However, I can't get the same fluidity I had with the character controller...
I've activated interpolation, set the time step to 0.01, tried to separate my camera from my player, but nothing works...

It's really a problem of fluidity when I move forward at the same time as I turn the camera.

#
using System;
using UnityEditor;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    [SerializeField] private float sensitivity;
    [SerializeField] private GameObject playerCamera;

    private float _xRotation;
    private float _yRotation;

    private Vector3 PlayerMovementInput;
    public Rigidbody _rigidbody;
    public float speed;

    private Vector3 moveVector;
    private void Start()
    {
        _rigidbody.isKinematic = false;
        _rigidbody.freezeRotation = true;
        _rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
    }

    private void Update()
    {
        var mouseY = Input.GetAxis("Mouse Y") * sensitivity;
        var mouseX = Input.GetAxis("Mouse X") * sensitivity;
        
        _xRotation -= mouseY;
        _yRotation += mouseX;

        _xRotation = Mathf.Clamp(_xRotation, -90f, 90f);
        PlayerMovementInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
    }

    private void FixedUpdate()
    {
        MovePlayer();
        RotateCamera();
    }

    private void RotateCamera()
    {
        transform.rotation = Quaternion.Euler(0, _yRotation, 0);
        playerCamera.transform.localRotation = Quaternion.Euler(_xRotation, 0, 0);
    }
    
    private void MovePlayer()
    {
        moveVector = transform.TransformDirection(PlayerMovementInput) * speed;
        _rigidbody.MovePosition(_rigidbody.position + moveVector * Time.fixedDeltaTime);
    }
}
slender nymph
#

you're breaking interpolation by assigning the transform.rotation

woven otter
#

hum

#

ok, so, i need to use MoveRotation ?

hexed dove
#

hello i am making a finite state machine which depends on a tickManager. I want my states to change every tick. But currently, it doesn't work because it doesn't detect the boolean to true.

thank you for taking some of your time...

polar acorn
#

This is a lot of code to comb through for a "doesn't work" check, what's the specific problem? Which code is doing something you don't expect? What should it be doing instead?

slender nymph
# woven otter ok, so, i need to use MoveRotation ?

MoveRotation may not be what you want, it likely won't feel very satisfying for players since it moves it to the desired rotation over time to the next physics update. you could probably get away with assigning the rigidbody.rotation, but i also recommend switching to cinemachine for the camera logic

hexed dove
#

But currently it just doens’t detect the OnTick bool in the tickManager because it changes too fast from true to false

polar acorn
#

Share the !code in a bin site so it can be searched

eternal falconBOT
hexed dove
#
woven otter
uneven plover
#

Hello, I need help to access some things of another script, I have this if :

if (lCollided.CompareTag(Tag)) {}

that return true and there is multiple object that I detect that have those tags, all the objects have the same script that contains a bool and a function that change the value of the bool. How can I call the function and get the value of the bool in my first script ?

Im not sure that Ive been clear, Im not the best english speaker
thx for your help

woven otter
#

collision.gameObject.Getcomponent<YourScript>().bool_var

uneven plover
#

perfect thank you !

stuck monolith
#

hi i made thait but i can use using UnityEngine;
using UnityEngine.XR;
using UnityEngine.XR.Interaction.Toolkit;

public class ArmBasedLocomotion : MonoBehaviour
{
public XRController leftController; // Reference to the left controller
public XRController rightController; // Reference to the right controller
public float movementSpeed = 2f; // Movement speed
public Transform playerBody; // To rotate the player's body

private Vector2 leftInput, rightInput; // Input data from controllers

void Update()
{
    // Get input from both controllers' joysticks (2D axis)
    leftController.inputDevice.TryGetFeatureValue(CommonUsages.primary2DAxis, out leftInput);
    rightController.inputDevice.TryGetFeatureValue(CommonUsages.primary2DAxis, out rightInput);

    // Combine both controller inputs to create movement direction
    Vector3 movement = new Vector3(leftInput.x + rightInput.x, 0, leftInput.y + rightInput.y) * movementSpeed * Time.deltaTime;

    // Move the player in the direction of the joystick input
    transform.Translate(movement);

    // Optionally, rotate the player body based on input
    if (leftInput.x != 0 || rightInput.x != 0)
    {
        // Rotate based on joystick movement (left or right)
        float turnAmount = (leftInput.x + rightInput.x) * movementSpeed * Time.deltaTime;
        playerBody.Rotate(0, turnAmount, 0);
    }
}

}

#

it make a lot of lag

nocturne parcel
#

!code

eternal falconBOT
nocturne parcel
stuck monolith
#

It does on VR

#

And developing a gorilla tag fan game

#

That is the player movement

nocturne parcel
#

Well, I'd wrap it in an if and then go from there
if (leftController.inputDevice.TryGetFeatureValue(CommonUsages.primary2DAxis, out leftInput) ||
rightController.inputDevice.TryGetFeatureValue(CommonUsages.primary2DAxis, out rightInput))

stuck monolith
#

can @nocturne parcel do you have a GorillaLocomotion temply it can use

weary saddle
#

i keep getting this error ArgumentException: Kernel 'KEyeHistogramClear' not found.
UnityEngine.Rendering.PostProcessing.LogHistogram.Generate (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/Utils/LogHistogram.cs:25)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.RenderBuiltins (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context, System.Boolean isFinalPass, System.Int32 releaseTargetAfterUse, System.Int32 eye) (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/PostProcessLayer.cs:1254)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.Render (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/PostProcessLayer.cs:1091)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.BuildCommandBuffers () (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/PostProcessLayer.cs:699)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.OnPreCull () (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/PostProcessLayer.cs:493)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

leaden cliff
#

Hi, I am making a top down table tennis game and I use animationCurves to simulate the bouncing of the ball on the table. Everything was working fine until I added the check if the ball executed keyframe 3 of its animationCurve within the trigger area of the table, to credit points differently to each player. Now it doesn't work anymore, the animationCurve is not executed, the ServeMode is not activated either, the only thing that works are the physics between the players and the ball. script: https://hatebin.com/bkhoqnwfgc

polar acorn
eternal falconBOT
stuck monolith
#

no lag

polar acorn
sour fulcrum
#

Does Unity provide any global event/indication of game starting?

#

(Yes, RuntimeInitializeOnLoad is what I'm looking for 🦆)

opaque cairn
#

I finished my movement finally. Feels goated. First project movement so it will be the first iteration of it's kind, but I feel I made accelerated steps in my understanding.

fierce geode
#

Is there anyway in code to put a child object in a specific slot, like if you wanted something to be specifically the second child.

summer fractal
#

Does anyone else have trouble downloading packages from git? I just get an error saying there was a problem. I got the error a ton of times in a row, restarted my computer and it worked. Now I’m getting the error again. Do I need to do something with my git installation?

radiant glen
#

Trying to get this image behind the text any ideas how to do it? Cant seem to get it to work!

fierce geode
radiant glen
queen adder
cosmic dagger
#

check the Tranform component in the Unity !docs for the method(s) . . .

eternal falconBOT
pastel dove
#

Sorry I'm not sure which channel to ask this in but the localization package is making my project stuck on importing assets when playtesting

#

It's always after creating an Asset Table

#

I'm trying to use Localized Sprite Event

#

it sometimes works and it sometimes doesnt

#

literally no changes at all to script

#

it just doesnt work

ember tangle
#

I'm trying to pass a function as an argument but I cant get it to work, I tried using System.Action and using System.Action<>; like stack overflow said but it didn't work.

here is the function:

    {
        pointer = new PointerEventData(eventSystem);
        pointer.position = Input.mousePosition;

        //Create a list of Raycast Results
        List<RaycastResult> results = new List<RaycastResult>();

        //Raycast using the Graphics Raycaster and mouse click position
        raycaster.Raycast(pointer, results);

        //For every result returned, output the name of the GameObject on the Canvas hit by the Ray
        foreach (var result in results)
        {
            if (result.gameObject.CompareTag("ItemPane"))
            {
                function(result.gameObject);
            }
        }
    }```
rich adder
ember tangle
#

This code gets repeated across 5 functions in almost the same manner and I though that instead I just call the InteractWithItemPane() and pass the relevant function in.

cosmic dagger
ember tangle
#

ie ```public void UIOnMouseDoubleClick()
{
pointer = new PointerEventData(eventSystem);
pointer.position = Input.mousePosition;

//Create a list of Raycast Results
List<RaycastResult> results = new List<RaycastResult>();

//Raycast using the Graphics Raycaster and mouse click position
raycaster.Raycast(pointer, results);

//For every result returned, output the name of the GameObject on the Canvas hit by the Ray
foreach (var result in results)
{
    if (result.gameObject.CompareTag("ItemPane"))
    {
        inventory.UseItemPane(result.gameObject);
    }
}

}```

rich adder
#

oh I see what you want to do..

ember tangle
#

My end goal is to have something like InteractWithItemPane(SingleClick()) InteractWithItemPane(DoubleClick()) InteractWithItemPane(MouseUp()) etc

rich adder
#

when you pass function you don't add the ()

#

() is for calling

cosmic dagger
#

it's prolly just a syntax issue . . .

ember tangle
#

its a delegate right?

cosmic dagger
#

() is the invocation . . .

obtuse quarry
#

I'm wondering if this pathfinding algorithm is good

#

So theres obviously a cell grid, theres a moving node (you) and the target node (destination)

#

You check all open nodes in each cardinal direction from the moving node whos closest to the target node, and move the moving node there

#

And continue until you reach the target node

#

Is this a good pathfinding algorithm? and is there already a name for this? Its the simplest (i think) so I'm assuming its known

rich adder
#

they have so many

#

Dijkstra, A* etc.

obtuse quarry
#

Is the one im describing still good even if its simple?

#

Or should I like... not use this one

oak kelp
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

rich adder
obtuse quarry
#

okay

#

thanks for the advice

eager spindle
#

is there a way to make boxfill any faster? I created a 500x500 small grid and it already takes a while to fill

eager spindle
naive pawn
#

not sure i'd call that small

bold thicket
#
public class CameraRotation : MonoBehaviour
{
    public CinemachineVirtualCamera vcam;
    public Transform target;
    public void cameraMovement()
    {
        target.rotation = vcam.transform.rotation;
    }
}
#

Hey all, I'm trying to get my cinemachine virtual camera to rotate the character body but it doesn't seem to work as simply as I thought it'd be. What's the alternative method to this?

ivory bobcat
bold thicket
#

They're pretty random values, I don't know how to make sense of it.

#

However, it seems the values change significantly when I move around rather than when I turn the camera which is weird?

queen adder
#

And change localRotation

bold thicket
#

like this?

#

still doesn't want to rotate 😦

queen adder
#

Have you changed rotation to localRotation of body?

bold thicket
#
    public void cameraMovement()
    {
        
        target.localRotation = vcam.transform.localRotation;
        
    }
#

should it be like that or target.rotation = vcam.transform.localrotation?

#

sorry i haven't quite got a handle on local vs global yet

queen adder
#

Im not advanced btw

bold thicket
#

doesn't want to rotate 😦

#

wait i don't think Cinemachines input provider when used for camera movement actually rotates the camera

#

because as i move it in game scene, the inspector rotation values stay 0 FeelsThinkingMan

onyx tusk
#

how 2 make 2d objects clickable? only througth button conponent?

bold thicket
#

did you get it to work?

queen adder
#

i couldt find cinemachine, instead used camera.

bold thicket
#

ah okay, i started with normal camera but was told to use cinemachine

burnt vapor
#

Or whatever this is

#

Literaly never seen this before

shadow pond
burnt vapor
#

This is the channel you need then

shadow pond
#

k got it

burnt vapor
#

Better chance of an answer there since there's likely not many people familiar with this here

shadow pond
#

ok

#

i delet message now

buoyant finch
#

hello everyone I have made this but the hp reduces drastically

astral falcon
buoyant finch
#
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class HPBar : MonoBehaviour
{
    [SerializeField] Image healthImage; // Reference to the Health image
    public float maxHealth = 100f;
    private float currentHealth;

    void Start()
    {
        SetHP(maxHealth);
    }

    public void SetHP(float hp)
    {
        currentHealth = Mathf.Clamp(hp, 0, maxHealth); // Clamp health between 0 and maxHealth
        UpdateHealthBar();
    }

    public void SetHPSmooth(float newHP)
    {
        StartCoroutine(UpdateHealthBarSmoothly(newHP));
    }

    private void UpdateHealthBar()
    {
        healthImage.fillAmount = currentHealth / maxHealth;
    }

    private IEnumerator UpdateHealthBarSmoothly(float newHP)
    {
        float oldHP = currentHealth;
        currentHealth = Mathf.Clamp(newHP, 0, maxHealth);
        float elapsed = 0f;
        float duration = 0.5f; // Duration for smooth transition

        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float t = Mathf.SmoothStep(0, 1, elapsed / duration); // Smooth step for ease in/out
            healthImage.fillAmount = Mathf.Lerp(oldHP / maxHealth, currentHealth / maxHealth, t);
            yield return null;
        }

        healthImage.fillAmount = currentHealth / maxHealth; // Ensure the final value is set
    }
}

hp bar script

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class BattleHud : MonoBehaviour
{
    [SerializeField] Text nameText;
    [SerializeField] Text levelText;
    [SerializeField] HPBar hpBar;

    Pokemon _pokemon;

    public void SetData(Pokemon pokemon)
    {
        _pokemon = pokemon; // Assign _pokemon here
        nameText.text = pokemon.Base.Name;
        levelText.text = ":L " + pokemon.Level;
        hpBar.SetHP((float)pokemon.HP / pokemon.MaxHp);
    }

    public void UpdateHP()
    {
        if (_pokemon == null)
        {
            Debug.LogError("Pokemon is null in UpdateHP! Ensure SetData is called before UpdateHP.");
            return;
        }
        hpBar.SetHPSmooth((float)_pokemon.HP / _pokemon.MaxHp);
    }
}

battlehud and battlesystem scripts

astral falcon
#

Please !code if you going for large code blocks

eternal falconBOT
buoyant finch
#

@astral falcon

#

Sorry for the ping

astral falcon
#

yeh, please dont do that

astral falcon
buoyant finch
astral falcon
umbral bough
#

Hi, not sure if this is a right channel to post this q, but yeah, let me know if I should move it.
Would it be possible to get a system font, say by a name(should be possible w c# if I am not mistaken), somehow feed it to the tmp font asset creator, and spit out a usable font at runtime?
I don't need any code examples or anything, just your opinions on if it's is possible or not.

buoyant finch
umbral bough
#

Also twentacle, I said that I was gonna let you know if I fixed the issue, I have thanks to this server: #1306527853982253079
Thanks again for your previous help!

queen wren
#

For some reason VS didn't know that Unity's method like Awake, Update, OnCollider and so on will gets called by Unity, and mark them as Unused.

I've regenerate the project files a couple of times but it's useless.
Any advice to fix it?

queen adder
#

Unity pcg

queen wren
languid spire
queen wren
teal viper
# queen wren

I think it's an issue with the latest VS patch.
Might be that the unity vs support package needs updating.

queen wren
#

it's not "that big" issue just a little bit annoying. 😁

queen wren
teal viper
queen wren
queen wren
obtuse quarry
#

is coding your own pathfinding system considered "beginner"?

#

im having a hard time with doing it

teal viper
#

It can get pretty advanced depending on what you're trying to do.

obtuse quarry
#

i thought it was gonna be easier than this

#

but i might be close to finishing it

#

im not sure yet

teal viper
#

Sounds contradictory

obtuse quarry
#

im still not sure how "good" the way im doing pathfinding is

its simple, i just set the position of the pathfinder to the neighbour who has the cheapest fcost

#

it sorta works

#

i mean it works amazing when there are no obstacles

#

goes to show that "simple" doesnt mean "good"

#

okay i think this part of my code is failing:

public List<Cell> GetNeighbouringCells() {
        List<Cell> ret = new List<Cell>();
        foreach (Cell cell in cells) {
            if (cell.transform.position == transform.position) continue;
            if (!cell.blocked) continue;
            if (Vector3.Distance(cell.transform.position, transform.position) > 1.5f) continue;
            cell.G = (int)(Vector3.Distance(cell.transform.position, transform.position) * 10);
            cell.H = (int)(Vector3.Distance(cell.transform.position, destination.position) * 10);
            cell.transform.name = $"{cell.F}";
            ret.Add(cell);
        }
        return ret;
    }```
#

oh i think i found the issue

#

yay i found the issue, and have successfully moved back to my original code

#

i just have to fix when it doesnt work around obstacles

weak cedar
#

The c# extension is broken, I reverted to the last update because of that

hexed terrace
bright siren
#

noticed this - at least it is a recognised bug, but seems MS often miss things with the plugin

hexed terrace
#

It's a VS update issue, not so much the VS Unity package... they probably don't test VS updates with Unity things?

vague adder
#

whats wrong? the instructor in the course wrote the same thing with no trouble

hexed terrace
#

maybe finish typing the method and see?

vague adder
devout flume
vague adder
#

i usually mind the errors while writing but the tooltip for OnTriggerEnter didnt pop up while writing (even though it popped up in the course) so i got suspicious

languid spire
burnt vapor
vague adder
#

oh i didnt realise that

burnt vapor
#

This method should just have to be manually typed out

#

Especially since it's very specific

vague adder
#

i feel like it would take a lot of effort to switch apps

#

i was told that vs code is like the best

burnt vapor
#

Try VS or Rider and you will quickly figure out that this is likely the case

#

VSCode is the worst one. It's a nice general text editor but not a proper IDE for C# or Unity

vague adder
#

alright ill switch to VS

#

thanks

hexed dove
#

https://pastebin.com/ELLASPuY : Cube Code.
https://pastebin.com/xFWkmjmz : TickManager Code.

Hello, i am trying to make a cube rolling game. For that, i made a tickmanager that sends an event each tick to the cube. On each tick, the cube changes state. I have an issue when the cube goes on a conveyor, i would like it to stop after hitting the ground again. i can't manage to do it. With all of what i tried, the cube just bugs out...

If you need more information just ask !
thank you for taking some of your time

rocky canyon
#

what do you mean by "bugs out"
whats happening as opposed to whats supposed to happen?
can u clarify a bit

hexed dove
#

either the cube teleports to the next conveyor destination, either he just teleports back to the acutal conveyor

#

i tried casting a raycast inside of the DoActionConveyorMove() to see if it hits any conveyor but it doesn't seem to work

solar torrent
#

UnityException: Transform child out of bounds
UnitSelectionManager.TriggerSelectionIndicator (UnityEngine.GameObject unit, System.Boolean isVisible) (at Assets/UnitSelectionManager.cs:128)
UnitSelectionManager.SelectByClicking (UnityEngine.GameObject unit) (at Assets/UnitSelectionManager.cs:117)
UnitSelectionManager.Update () (at Assets/UnitSelectionManager.cs:53)

#

idk what i did wrong

gleaming kraken
#

the code behind my game is so messy but it works. I need to fix that mentality and actually refactor it but refactoring is incredibly boring. Any tips on making refactoring a little more entertaining, or do I just have to bite the bullet here?

burnt vapor
#

The stacktrace has been so nice as to tell you where it happened. If you want help here I suggest you share the relevant !code inside UnitSelectionManager.cs.

eternal falconBOT
solar torrent
#

yea homie imma honest idk what that means i assigend the child to the index of 1

#

ne of 0

burnt vapor
#

Can't say much without your code

#

Apart from the obvious

hexed dove
#

can anyone help with my issue pls ?

solar torrent
#

i think it works

solar torrent
burnt vapor
solar torrent
#

ok

burnt vapor
#

So, do you understand the concept of stacktraces?

solar torrent
#

erm no like a stack as in a paramater

burnt vapor
#

So the last call before it broke was in Assets/UnitSelectionManager.cs:128

solar torrent
#

exception as in error?

burnt vapor
#

Yes

solar torrent
#

erm so i clicked than it like broke

burnt vapor
#

In your case this line is unit.transform.GetChild(0).gameObject.SetActive(isVisible);

solar torrent
#

after like a few clicks

burnt vapor
#

If the transform has no child, or the index argument has a value greater than the number of children then an error will be generated. In this case "Transform child out of bounds" error will be given. The number of children can be provided by childCount.

#

So one thing you can do is check if there's at least 1 child with childCount

#

But in your case there should always be a child I assume?

solar torrent
#

but there is only 1

#

so i said 0

burnt vapor
#

That's correct

#

But somehow the gameobject ends up with no child

#

If I were you, I would start logging the gameobject that comes in.

    private void TriggerSelectionIndicator(GameObject unit, bool isVisible)
    {
        Debug.Log($"TriggerSelectionIndicator: {unit.childCount}", unit);
        unit.transform.GetChild(0).gameObject.SetActive(isVisible);
    }

Then, when the exception is thrown you press the log message that is logged in the console

#

When pressed, it navigates to the gameobject that was passed

#

Take a look and you will see it has no children inside

solar torrent
#

wait so

#

wait wait wait i looked but the child nevers goes away when i press play

burnt vapor
#

It's not supposed to go away, is it?

#

Don't debug by looking, debug with proof

#

Your proof is that log message that validates that it's actually using your gameobject

#

I updated the log message, use that instead

solar torrent
#

the child should uncheck after i unselect and that works but it just randomly bearks

#

breaks

vague adder
#

its so good

#

it took me just 10 seconds to realise how good the tooltip is

solar torrent
silk night
vague adder
#

the ''copilot'' word is enough for me to fall inlove with it

rocky canyon
#

theres free ones out there. not sure about copilot.. i would assume its a free feature.. i use vscode and codeium..

theres something so helpful about being about to type out my variables and method names and have my assistant be like:
"oh, i see what ur trying to do here, let me save u some trouble and type out the basic boilerplate for ya"

silk night
#

copilot has a 30day free demo

rocky canyon
#

there ya are ^

vague adder
#

30d aint enough allat

silk night
#

its $10 per month after

rocky canyon
#

it defaults everything to debug.log as of now. b/c thats what ive been doing lately..
but back when i was dealing w/ rigidbodies it was completing that.. and same w/ others

#

in love ❤️ lol

silk night
#

sometimes it does really neat things (only typed the function name here)

silk night
#

other times... it does this

rocky canyon
#

sooo good

rocky canyon
#

pretty good about making lists and arrays

timber tide
#

I don't mind hint/suggestions but auto complete will usually add exactly what I didnt want then proceed to add the namespace I have to clean up later

naive pawn
rocky canyon
#

tbh i havent had the best of luck using context..

#

like supposedly i can ask it a question and add my line number..

#

but most times it gets all generic on me..

silk night
#

oh copilots context chat is really good

rocky canyon
#

i bet.. 😭 lol. that pay to win

silk night
#

found some really nasty to debug bugs by just asking copilot what it thinks could be an error source

#

company pays 😄

timber tide
#

most useful thing that I found using it is formatting enums into bit flags

minor hull
#

Just starting out on Unity, I added controller movement to my player character script, but it seems to have disabled my normal keyboard movement. What can I do to fix it?

rocky canyon
minor hull
steep rose
#

it writing code for you though is horrid

#

maybe for refactoring

silk night
rocky canyon
#

do you have the new input system set as the default input method?

minor hull
#

There's a default input method?

steep rose
#

Old input system

#

for unity 6 it might be the new one

silk night
minor hull
#

It's worth noting that I'm following one of the unity tutorials for a 2D adventure game

rocky canyon
steep rose
#

yes use gogle, as gogle is the best search engine

rocky canyon
timber tide
#

stackoverflow about to become deprecated with the partnership with openAI. Is true through. Why would you want to continue using it nowadays if they're just going to sell your data haha

silk night
# steep rose use google

oh i wont let it write stuff that i dont understand, but ill gladly accept if it saves me 30s to type out a function 😄

minor hull
#

I'm pretty sure I'm using the new input system

rocky canyon
steep rose
rocky canyon
#

if its set to "Old" it wont work.. so use the new one or both

minor hull
#

This is what I have atm

silk night
rocky canyon
silk night
minor hull
#

Existing actions... I think

silk night
#

uhh what the hell is that 😄 can you show us your inputactions? should be in the project settings

silk night
#

check if the move vector is != zero

#

or add the move values together (+ normalize them so you are not double as fast if both go right for example)

minor hull
silk night
steep rose
#

I mean it can do it but 😬

naive pawn
rocky canyon
#

should create a class you can use for ur inputs

silk night
rocky canyon
steep rose
silk night
#

me neither, but seems to work somehow 😄 ¯_(ツ)_/¯

rocky canyon
#

i thought there was two ways to do it..

  1. you generate the c# class and use that
  2. you use the player input component
steep rose
#

it hurts seeing it happen

minor hull
#

I'm following a tutorial by unity right now, and these were the steps it gave me

rocky canyon
#

well props to you for starting w/ the new input system

minor hull
#

I'm sure I'll figure out more efficient methods as I keep learning

minor hull
steep rose
#

if he is using unity 6 it should be the default selected

vague adder
silk night
#

the only other package that they should finally include by default is Cinemachine

vague adder
rocky canyon
#

might be helpful when learning/ playing around w/ the new input system

minor hull
#

Great, thanks!

hexed dove
#

https://pastebin.com/ELLASPuY : Cube Code.
https://pastebin.com/xFWkmjmz : TickManager Code.

Hello, i am trying to make a cube rolling game. For that, i made a tickmanager that sends an event each tick to the cube. On each tick, the cube changes state. I have an issue when the cube goes on a conveyor, i would like it to stop after hitting the ground again. i can't manage to do it. With all of what i tried, the cube just bugs out... either the cube teleports to the next conveyor destination, either he just teleports back to the acutal conveyor. tried casting a raycast inside of the DoActionConveyorMove() to see if it hits any conveyor but it doesn't seem to work

If you need more information just ask !
thank you for taking some of your time

solar torrent
#

ok I'm back at beginner sir

#

thatguy777

#

where are you homie

burnt vapor
#

You were talking to me

#

I told you to debug the issue. Did you debug it?

strong wren
#

Ask a question if you have one

solar torrent
#

yea

#

i did

burnt vapor
#

Show me the console when the exception happens

solar torrent
#

it does not tell anything

burnt vapor
#

Except it will

solar torrent
#

ok should i cann you then bc i cant send the video

burnt vapor
#

Share a screenshot

#

Full console, with the exception and the last log message

rocky canyon
#

Win + Shift + S to screenshot portions of the screen

Full Console, w/ the last log

solar torrent
#

ok gimme 2 sec my dog is griefing

real forum
#

Hey guys! I'm completely new to game dev and C# (I work mainly on ML using Python). It's been about 3 days since I started, and I understand everything about the Unity Editor UI and the components system and everything, but I don't understand the coding part at all. Does anybody know any useful resources that helped you learn Unity and C# scripting.

eternal falconBOT
#

:teacher: Unity Learn ↗

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

real forum
ebon marlin
#

throwing myself at a pong project to learn unity, it works but is there a better way to do this?

private void FixedUpdate()
    {
        rb.MovePosition(rb.position + _moveDirection * Time.fixedDeltaTime);
        if (transform.position.x < -8.5)
        {
            transform.position = new Vector2(-8.5f, transform.position.y);
            _moveDirection.x *= -1;
        }
        else if (transform.position.x > 8.5)
        {
            transform.position = new Vector2(8.5f, transform.position.y);
            _moveDirection.x *= -1;
        }
        else if (transform.position.y < -4.5)
        {
            transform.position = new Vector2(transform.position.x, -4.5f);
            _moveDirection.y *= -1;
        }
        else if (transform.position.y > 4.5)
        {
            transform.position = new Vector2(transform.position.x, 4.5f);
            _moveDirection.y *= -1;
        }
    }

currently letting the ball bounce off all walls just to test it out