#πŸ’»β”ƒcode-beginner

1 messages Β· Page 21 of 1

smoky ledge
#

This is what it looks like

static cedar
#

I believe trying to set it on Euler angles can cause other values to change as well.
I had this happen and they certainly don't match the inspector.

static cedar
#

Unlike in the inspector where u just see the raw values, the Euler angles I guess let's say readapt the values. If I remember correctly, you won't see 360 degrees in Euler angles for example.

smoky ledge
static cedar
#

I tried rotating something on the X axis and whenever it clocks to 180 or 360, y is somehow affect. -_-

rich adder
cosmic dagger
smoky ledge
cosmic dagger
rich adder
#

spoiler alert: they did not read

smoky ledge
#

Bits of it

cosmic dagger
smoky ledge
#

Yes, let me go back and read it

grim tulip
#

Me=code beginner

rich adder
#

fitting for channel

grim tulip
#

Ikr πŸ€“

#

Anywayyy

#

I shall set my stuff up until I Get a pc to actually start coding on πŸ˜ƒ

cosmic dagger
#

you can code on a crappy pc . . .

grim tulip
#

Yea but u can’t make a game on one

#

Or your pc is gonna go boom with one asset

rich adder
cosmic dagger
#

you can, just not some fancy, shmancy, AAA graphics one . . . . . .

grim tulip
#

my eyes have opened a new

grim tulip
cosmic dagger
#

not really. you heard of indie games?

rich adder
#

a good game != good graphics

grim tulip
#

I thunk

eternal needle
rich adder
grim tulip
rich adder
grim tulip
#

Oh wait

#

Wrong topic

grim tulip
#

Neva heard of it

rich adder
#

how you never heard of heartstone

grim tulip
#

Idk

teal viper
#

RimWorld, terraria, Minecraft

rich adder
#

ig ur not into card games πŸ˜›

static cedar
grim tulip
#

Oh I just looked at it

#

Yea no card games

grim tulip
#

I love kenshi to πŸ™‚ but idk if it was made from Unity

rich adder
static cedar
#

Aye.

teal viper
#

Oh, was the discussion about games made in unity?πŸ˜…

grim tulip
#

BRUH

teal viper
#

I thought it was about good games != graphics.

grim tulip
#

Got my hopes up for nothin πŸ˜”

teal viper
grim tulip
#

Well jokes on you I already have a game that I wanna make

#

But I has no skills to make t

rich adder
#

time to get learnin

grim tulip
#

YUH

#

But like

#

πŸ‘€

#

Not rn

#

Cause I tired

static cedar
#

Is ultra kill made in unity?

rich adder
#

yus

grim tulip
static cedar
#

I'm genuinely surprised.

#

I can't even pay for games. :P

grim tulip
#

I shall rant about my game idea

#

TOMORROW

#

bye people πŸ™‚

cosmic dagger
grim tulip
#

OKAY

#

Tomorrow I shall rant there

violet topaz
#
public class LookAtMouse : MonoBehaviour
{
    
    // Update is called once per frame
    void Update()
    {
        var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
        var angle = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    }
} ```

 how do I make the player look at the mouse. right now its looking the opposite way
grim tulip
#

But today is a Zzzzzz

cosmic dagger
teal viper
#

Me😭

cosmic dagger
#

just flip it . . .

violet topaz
#

ok, sorry didnt see the message i wasnt at my comupter

smoky ledge
#

@cosmic dagger Thank you, I'm absolutely technologically bankrupt. I finally got it working

topaz mortar
#

I have a Combat Script with a reference to my Character Script
While combat is happening and the character kills a monster the Combat Script will send experience to the Chracter Script
But on level up, I need the Character Script to tell the Combat Script to re-calculate damage
How would I go about this?

cosmic dagger
#

use an event . . .

topaz mortar
#

that's the Invoke thingie not?

cosmic dagger
#

try to keep the character and combat mechanic separate (non-dependent) from each other . . .

topaz mortar
#

so I should re-calc damage before every attack?

cosmic dagger
#

but why should the character script inform the combat system to re-calc after a level up?

topaz mortar
#

because the character script has the stats and the stats determine the damage

teal viper
#

Yeah, calculating the damage for each attack would be the most reliable way.

cosmic dagger
teal viper
#

You could use a cache and "isDirty" kind of system, but that might be over engineering.

topaz mortar
cosmic dagger
#

how are your stats stored? i figured it'd be a class or collection of stats which would be a reference type . . .

summer stump
topaz mortar
#

I calc damage in the Start() function on combat script

summer stump
topaz mortar
#

nope

cosmic dagger
summer stump
cosmic dagger
#

damage should be calculated on every attack . . .

topaz mortar
teal viper
#

What about buffs or items?

cosmic dagger
#

what if a specific attack has a buff or debuff?

topaz mortar
#

haven't gotten that far yet πŸ˜›

#

it's an idle game, so damage really shouldn't change often

cosmic dagger
#

when you attack, you should call a method to calculate the damage and send that to the enemy . . .

topaz mortar
#

I think the event makes more sense

summer stump
#

It won't cost much at all, and that would be quite reliable.

Then you can just change the stuff your damage function uses to calculate damage from

topaz mortar
#

true

#

I'll just go with that for now πŸ™‚

#

C# is not like JavaScript right?
If I do

DamageMonster();```
It will finish the 1st function before executing the second one right?
eternal needle
topaz mortar
#

no javascript will execute them at the same time

#

that language is crazy

cosmic dagger
#

it just calls each line . . .

topaz mortar
#

yeah that

#

but it often results in the 2nd function getting called before the 1st one has finished

teal viper
eternal needle
#

im super curious where you got this idea from, unless you were unknowingly using async

summer stump
#

There is also asynchronous code in C#

eternal needle
#

because literally nothing will run at the same time

topaz mortar
teal viper
#

Wat

summer stump
#

No

eternal needle
#

you 100% should not be throwing out definitive statements like that

cosmic dagger
topaz mortar
teal viper
#

It could've been the engine or the framework you were using that were working async by default. The language itself is not async by default.

eternal needle
#

πŸ€” even i am confused what you are now trying to claim. you used async, but are claiming regular functions will run at the same time

topaz mortar
#

I might have the terms backwards

rich adder
#

how did you code a game not knowing this?

summer stump
topaz mortar
eternal needle
#

you are still wrong on that

teal viper
#

It depends on the definition/implementation of your functions. If they are async, it will indeed work as you describe.

summer stump
#

But again, that is explictly telling them to work that way. It does NOT work that way by default.

I have used JS a LOT and yes, it will only work that way with async.

topaz mortar
#

my terminology might be wrong, but my point is valid

eternal needle
#

what no, its still wrong

topaz mortar
#

JS by default does not wait for that 1st function to complete

summer stump
topaz mortar
#

go try it

summer stump
eternal needle
#

And i am not a fool πŸ€·β€β™‚οΈ

topaz mortar
#

I'm looking at google on my 2nd screen and it supports my claim

#

and I've made games in Node.js and ran into this exact issue

buoyant knot
#

gif of the funny black man walking into a burning appartment with a pizza

eternal needle
#

alright pack it up boys, google supports his claim

teal viper
eternal needle
#

or have been using functions that were async unknowingly

teal viper
#

Node js has promises, callbacks and other stuff that runs async. So maybe you're confusing with the framework implementation.

rich adder
#

seems legit

summer stump
rich adder
#

or people legit just say shit to cause a reaction xD

frozen mantle
#

Im a bit embarrased that i can't seem to figure out the logic im trying to go for here, but what im trying to do is run through a list of gameObjects, and if their names are not "x" or "y", then go ahead and enable them. The issue i'm running into is that when i write this out in an if statement (child.gameObject.name != "x" || child.gameObject.name != "y") i get the issue that even if the gameObject name is x, it still gets enabled because its name is not y, so it passes the boolean.

in other words, i want to enable all objects except the two that are named "x" or "y". Is there a way to do it in 1 if statemnet, or do i have to use a nested if statement?

topaz mortar
#

pretty sure u just use && instead of ||?

summer stump
# topaz mortar I'm looking at google on my 2nd screen and it supports my claim

Just trying to be helpful, but this site explains it well:
https://www.freecodecamp.org/news/asynchronous-javascript-explained/

"By default, JavaScript is a synchronous, single threaded programming language. This means that instructions can only run one after another, and not in parallel."

Async is cool, and useful. C# can do it too.

Just trying to help.

Edit: also, Unity has "Jobs" which enables highly performant threading, and it is AWESOME. They aren't necessarily multithreaded, but it makes it easy to do

frozen mantle
buoyant knot
#

sync is usually the default. You normally need to explicitly ask for async, because it’s otherwise not clear how you split the work.

frozen mantle
#

nah i'm just teasin'

topaz mortar
rich adder
#

async Function

#

can't read?

frozen mantle
#

reminder of the capabilities of JavaScript:

#

"wat"

cosmic dagger
# topaz mortar

it's speaks of operations, not the entire language and it says "some" . . .

rich adder
#

that page is nonense, they talk about async function but fetchData isn't marked as async

#

yet says the function is async

#

//DataFetching logic here is probably in the assumption some kind of async call is going on there to the API

summer stump
topaz mortar
#

yeah because some behaviour in JS is async by default
maybe it's just API calls & database calls or something
but I've 100% run into this issue in the past, it's been years though
anyway, I'm done with this subject

charred spoke
topaz mortar
#

why would JS have async await if not for this exact issue?

summer stump
rich adder
cosmic dagger
summer stump
frozen mantle
#

idk why i replied to you random, sorry

topaz mortar
frozen mantle
#

but here's the site they were referencing, it seems

topaz mortar
#

ah no they use async

#

I don't remember this shit, it was years ago

#

I just know I ran into this issue

topaz mortar
#

yeah u were right, I probably used async in my function because I needed to wait for API or database

charred spoke
#

There I fucking typed js on my phone for this

#

Its not async

topaz mortar
#

or just stop talking about it, I really don't care

charred spoke
#

It still will mot by async u less I make it

summer stump
charred spoke
#

Api and db calls are MADE to be async because of the longer response time

rich adder
topaz mortar
rich adder
charred spoke
#

Guys guys I was saying this all along I just didn’t remember cause it was years ago right

topaz mortar
#

assholes ...

charred spoke
#

Just admit you were wrong

#

Its okey

topaz mortar
#

I already did lol

frozen mantle
#

if a mod were here they would be peeved, ain't no JS gotta do with unity!

rich adder
#

πŸš”

cosmic dagger
rich adder
#

oh dont even offend JS like that xD

frozen mantle
#

i confuse

rich adder
#

unityscript = js like code for unity

#

back in the dayz

#

wasnt real JS tho

cosmic dagger
#

yep . . .

summer stump
#

One of the MULTIPLE scripting languages unity used notlikethis

frozen mantle
#

why did unity have a bespoke language?

#

what is this, GoDot?

#

Hey-oooooooooooo

rich adder
#

also BOO

#

clearly c# won

frozen mantle
frozen mantle
summer stump
charred spoke
#

I started with 3. somethibg

frozen mantle
charred spoke
#

The amount of js to c# translating from unity answers that I have done

charred spoke
#

I basically learned js by osmosis

frozen mantle
#

oh, you put a little squiting cat face with the name "at what cost"

summer stump
frozen mantle
#

ah ok\

#

i thought you were saying that converting the code from JS to C# was too costly or something

rich adder
#

in the end it all turns into bytecode UnityChanSleepy

silent vault
#

Hello, I'm using Unity 2022.3.9f1 and imported the Starter Asset Third Person Shooter with cinemachine. I've replaced the model by my own as explained in the video tutorial but my character is stuck in Falling animation despite being on the floor

#

Anyway to fix that ?

frozen mantle
#

random, but how come unity scripts don't define "System" as a name space?

frozen mantle
silent vault
frozen mantle
silent vault
#

Like this

#

Seems like grounded never changes to true

frozen mantle
#

did you change just the model? or did you mess with the collision box too?

silent vault
#

But my character capsule seems to be on the floor

#

Just the model

frozen mantle
#

is this a character controller?

silent vault
#

Oh I'm dumb... I forgot to change the "Ground" layer in the controller script like the documentation said. My bad. It's ok now

frozen mantle
#

ahh yeah that'll do it, lol

silent vault
#

Thanks πŸ˜‰

cunning rapids
#

Guys I have a problem with my weapon switching

cosmic dagger
charred spoke
summer stump
frozen mantle
cunning rapids
#

I'm recording it hold on

#

Sorry

cosmic dagger
#

i'd wait until you have everything ready before sending out a cryptic, open-ended message . . .

cunning rapids
#

When you switch weapons while reloading it disables the shooting for that weapon for some reason

rich adder
charred spoke
cunning rapids
frozen mantle
charred spoke
#

Perhaps care to share some relevant code

summer stump
rich adder
charred spoke
cosmic dagger
rich adder
summer stump
cosmic dagger
#

naw, it prolly says TimeSpan is not defined . . .

frozen mantle
cunning rapids
cosmic dagger
eternal falconBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

frozen mantle
frozen mantle
#

Quick Refactor?

summer stump
cunning rapids
# cosmic dagger !code
    private void Update()
    {
        if (!isReloading)
        {
            if (Input.GetButtonDown("Fire1") && Time.time >= nextFireTime && currentAmmo > 0)
            {
                isShooting = true;
                Shoot();
                currentAmmo--;
                nextFireTime = Time.time + 1f / fireRate;
            }

            if (Input.GetButtonUp("Fire1"))
            {
                isShooting = false;
            }

            if (isShooting && Time.time >= nextFireTime && currentAmmo > 0)
            {
                Shoot();
                currentAmmo--;
                nextFireTime = Time.time + 1f / fireRate;
            }

        }

        if (Input.GetKeyDown(KeyCode.R) && !isReloading && currentAmmo < magazineCapacity && currentAmmo > 0)
        {
            animator.Play(reloadAnimationName);
            Reload();
        }

        if (Input.GetKeyDown(KeyCode.R) && currentAmmo == 0 && !isReloading)
        {
            animator.Play(noAmmoAnimationName);
            NoAmmoReload();
        }
    }
rich adder
# frozen mantle Quick Refactor?

when it says It doesn't exist , you can press w/e shortcut quick refactor in vscode is, it adds namespace, should be the lightbulb icon

cosmic dagger
cunning rapids
#

Those are the respective reload coroutines and methods:

    private void Reload()
    {
        StartCoroutine(ReloadCoroutine());
    }
    
    private void NoAmmoReload()
    {
        StartCoroutine(NoAmmoReloadCoroutine());
    }

    private IEnumerator ReloadCoroutine()
    {
        isReloading = true;
        yield return new WaitForSeconds(AmmoSeconds);
        currentAmmo = magazineCapacity;
        isReloading = false;
    }

    private IEnumerator NoAmmoReloadCoroutine()
    {
        isReloading = true;
        yield return new WaitForSeconds(NoAmmoSeconds);
        currentAmmo = magazineCapacity;
        isReloading = false; 
    }
cosmic dagger
#

and the method to switch weapons . . .

cunning rapids
frozen mantle
summer stump
cosmic dagger
#

what's the problem? you can just add the namespace, done deal . . .

frozen mantle
#

ah ok

cosmic dagger
#

or use the fully qualifying name . . .

#

or an alias. many options . . .

rich adder
charred spoke
cosmic dagger
frozen mantle
cunning rapids
# charred spoke If you disable the entire gameObject that runs the Reload coroutine it will not ...

Oh yeah that's definitely the problem:

using UnityEngine;

public class WeaponSwap : MonoBehaviour
{
    public GameObject[] objectsToToggle;

    private void Update()
    {
        for (int i = 0; i < objectsToToggle.Length; i++)
        {
            if (Input.GetKeyDown(KeyCode.Alpha1 + i))
            {
                ToggleObjects(i);
            }
        }
    }

    private void ToggleObjects(int activeIndex)
    {
        for (int i = 0; i < objectsToToggle.Length; i++)
        {
            if (i == activeIndex)
            {
                objectsToToggle[i].SetActive(!objectsToToggle[i].activeSelf);
            }
            else
            {
                objectsToToggle[i].SetActive(false);
            }
        }
    }
}
cosmic dagger
cosmic dagger
summer stump
cosmic dagger
#

yeah, fix those edge cases . . .

cunning rapids
#

Also I feel like the script is pretty messy

frozen mantle
cunning rapids
#

What would you do for weapon-switching?

cosmic dagger
#

when you switch weapons, call the cancel method on the active weapon . . .

summer stump
cunning rapids
#

"Just set isReloading to false, but don't do the ammo"

This?

summer stump
#

Just don't add the additional ammo, and reset the bool

cunning rapids
#

And I can call the function using cs OnDisable
right?

cosmic dagger
frozen mantle
cunning rapids
cosmic dagger
cunning rapids
#

@summer stump what do you mean exactly by "but don't do the ammo"

frozen mantle
#

or were you replying to Aeth, and your reply just so happen to answer my question as well?

cosmic dagger
frozen mantle
#

oh, funny, i think you answered my question as well lol

cunning rapids
#
    private void CancelReload()
    {
        isReloading = false;
        currentAmmo = currentAmmo;
    }

Something like this should cut it, right?

#

@cosmic dagger

charred spoke
cosmic dagger
charred spoke
#

CurrentAmmo= currentAmmo does nothing

cosmic dagger
frozen mantle
cosmic dagger
cunning rapids
cosmic dagger
frozen mantle
cunning rapids
summer stump
cunning rapids
#

Just tried it

#

Doesn't work

frozen mantle
cosmic dagger
# cunning rapids Doesn't work

you shouldn't change the ammo count until after the reload is done. if you switch weapons during reload, the current ammo should not change at all . . .

cunning rapids
#

I think that's what my coroutines are already doing ```cs
private IEnumerator ReloadCoroutine()
{
isReloading = true;
yield return new WaitForSeconds(AmmoSeconds);
currentAmmo = magazineCapacity;
isReloading = false;
}

private IEnumerator NoAmmoReloadCoroutine()
{
    isReloading = true;
    yield return new WaitForSeconds(NoAmmoSeconds);
    currentAmmo = magazineCapacity;
    isReloading = false; 
}
cosmic dagger
#

so what's the problem with the ammo?

cunning rapids
#

Should I put the isReloading bool above the ammo set or will that change absolutely nothing?

queen adder
#

#βš›οΈβ”ƒphysics i asked a question in this channel not sure if it’s better suited for here if so lmk and i will move it

cunning rapids
cosmic dagger
cunning rapids
#

Didn't work unfortunately

#
    private void OnDisable()
    {
        animator.Rebind();
        CancelReload();
    }
#
    private void CancelReload()
    {
        isReloading = false;
    }
cosmic dagger
#

did you check if those methods were called? place logs in cancelReload and OnDisable . . .

cunning rapids
#

What should I log specifically?

cosmic dagger
#

anything. you're just testing if the method runs. the log will inform us it does cuz that line of code was executed . . .

#

just log the method name or smth . . .

cunning rapids
#
    private void CancelReload()
    {
        isReloading = false;
        Debug.Log(isReloading);
    }
```?
#
    private void OnDisable()
    {
        animator.Rebind();
        CancelReload();
        Debug.Log(isReloading);
    }
#

It should logically return false

cosmic dagger
#

yeah, but you should name it to know what value you're looking at . . .

cunning rapids
#
    private void CancelReload()
    {
        isReloading = false;
        Debug.Log("isReloading");
    }
cosmic dagger
#
Debug.Log($"<color=magenta>CancelReload</color> | isReloading: <color=cyan>{isReloading}</color>");
Debug.Log($"<color=magenta>OnDisable</color> | isReloading: <color=cyan>{isReloading}</color>");
cunning rapids
cosmic dagger
#

well, it sets it to false . . .

cunning rapids
#

Maybe if I handle the shooting with a seperate method and call it in ```cs
OnEnable

cosmic dagger
#

it still won't allow you to shoot when you switch back to the weapon?

cunning rapids
#

Yup

#

Didn't work

cosmic dagger
#

when you switch back is isReloading still false?

cunning rapids
#

How do I check that?

cosmic dagger
#

log the variable in OnEnable . . .

cunning rapids
#

Maybe I can just make my WeaponSwap script communicate with my Shooting script to disable itself while the animation is still playing?

cunning rapids
#

!code

eternal falconBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

frozen mantle
#

this is the nastiest, overly long line of code i've writen, but by jove it works:

#

||ScoreBoard.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = "Time:\t "+((int)TimeSpan.FromSeconds(currLevelStats.time).TotalMinutes).ToString()+":"+TimeSpan.FromSeconds(currLevelStats.time).Seconds.ToString("00");||

cunning rapids
#

This is the full code

rich adder
cunning rapids
rich adder
# frozen mantle No

πŸ₯± cs if(ScoreBoard.transform.GetChild(1).TryGetComponent(out TextMeshProUGUI text)) { text.text = $"Time: \t {(int)TimeSpan.FromSeconds(currLevelStats.time).TotalMinutes} : {TimeSpan.FromSeconds(currLevelStats.time).Seconds:00}"; }

summer stump
#

Nope, it's too late. You said No, and now it can't be changed.
Stop looking at it!

cunning rapids
#

@cosmic dagger I found the problem

#

I fixed it

#

Thank you

#

It turns out we were looking at the wrong value

#

We thought there was something wrong with the isReloading bool

#

In reality our fix worked, but the currentAmmo was simply 0

timber sundial
#

Hi! Is there a way to declare new variables for each enum? I have an enum of collectibles (coin, files etc.) and want to declare a new integer for each one but want to make it in a way where if I add a new enum it would automatically make a new integer for a counter of how many of those items are collected?

gaunt ice
#

idk if there way to "add" new value to enum in run time, but you can use Enum.getname.length to see how many value in enum

#

and you may need array, use enum as the index

cunning rapids
#

Guys

#

How do I handle grenade throwing when my grenade prefab explodes after a short delay

#

Which means after said short delay, Instantiating the object doesn't work anymore

fossil drum
cunning rapids
#

Because the prefab literally destroys itself

fossil drum
#

No, the prefab sits in your Assets folder, not in your scene.
It will never destroy it self.

cunning rapids
#

Oh right

#

I'm stupid

#

I unpacked it when I added it to the scene

cunning rapids
#

Guys, how do I anchor TMP to the bottom left of my screen

queen adder
#

is there a string to vector3 method?

#

that just the inverse of vec3.ToString()?

gaunt ice
#

no, since format is undefined

ashen ferry
#

u can make ur own ig

cunning rapids
#

Why is TMP not at the bottom left when I anchored it like this

gaunt ice
#

you have set pos x and y

#

btw not code question

light moss
cunning rapids
gaunt ice
#
if(player not in void){
  camera follows player
}
```now camera only follow pleyer if player is not falling into void
woven cradle
#

hey, could someone tell me how I can make a path along which the Enemies should move, and what I mean here is not specifically about marking lines or points, but the entire path in which the Enemies would move randomly when it comes to their appearance, but they always went towards the end of the path and when Ally appears on their way in a certain area, they cancel their further progress on this path, they will just start attacking him, I'm asking because I don't really know how to go about it, I've heard something about navmesh but I don't know if it's a good solution and I'm not entirely sure how it's supposed to work.

light moss
# cunning rapids Show us the camera script

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

public class CameraFollow : MonoBehaviour
{
public float FollowSpeed = 2f;
public float yOffset = 1f;
public Transform target;

// Update is called once per frame
void Update()
{
    Vector3 newPos = new Vector3(target.position.x, target.position.y + yOffset, -10f);
    transform.position = Vector3.Slerp(transform.position, newPos, FollowSpeed * Time.deltaTime);
}

}`

cunning rapids
light moss
#

yeah thats what I am trying to do right now

cunning rapids
#

It's easy

#

add this variable

#
public float stopFollowingYLevel = 10f;
#

and then the camera logic under this condition:

        if (target.position.y <= stopFollowingYLevel)
        {
            Vector3 newPos = new Vector3(target.position.x, target.position.y + yOffset, -10f);
            transform.position = Vector3.Slerp(transform.position, newPos, FollowSpeed * Time.deltaTime);
        }
#

another trick is you can add colliders under your map to define where the void starts

#

and if the camera triggers the colliders it stops following the player

eternal needle
# light moss yeah thats what I am trying to do right now

Doing it based on colliders is probably better. you can define areas where this happens so you arent limiting yourself to design around the Y value. Also itll allow you to have more complex level design.
You could have some event on the player, that the camera subscribes to, which happens when the player enters the kill area. Then another event for when it respawns to tell the camera to start following again

lethal relic
#

I have created a simple ScriptableObject. After doing some changes to the script, the .asset file no longer loads properly. How can I fix that?

#

Here's what it looks like:

#

Here's what it should look like;

wintry quarry
queen adder
quaint thicket
#

I'm trying to get my camera to rotate vertically without it becoming lopsided like in the picture. Any ideas?

        public static float rotationX = 0;
        public static Vector2 rotationLimits = new Vector2(80, -80); // Vertical rotation limits
        private static Vector3 offset = new Vector3(0f,0f,0f);

        void RotateCamera4(float x, float y)
        {
            Transform target = Object.PlayersMainObject[0].GameObject.transform;

            // Get the mouse input
            float mouseX = x * 2f;
            float mouseY = y * 2f;

            // Rotate the target horizontally
            Camera.main.transform.Rotate(Vector3.up * mouseX);

            // Rotate the camera vertically
            rotationX -= mouseY;
            rotationX = Mathf.Clamp(rotationX, rotationLimits.y, rotationLimits.x);
            // Camera.main.transform.Rotate(Vector3.left * mouseY);


            // Calculate the rotation quaternion
            Quaternion rotation = Quaternion.Euler(rotationX, target.eulerAngles.y, 0);

            // Calculate the new position of the camera based on the rotation and offset
            Vector3 newPosition = target.position + rotation * offset;

            // Apply the new position to the camera
            Camera.main.transform.position = newPosition;

            // Make the camera look at the target
            Camera.main.transform.LookAt(target);
        }```
neon ivy
#

I want a scene wide tick speed I can call functions in, my best idea is to make a coroutine call an event every x amount of milliseconds and to then subscribe to this event from other scripts. does anyone have a better idea on how to implement tick speed?

charred spoke
neon ivy
#

thanks

slender cargo
#

Does anyone know how this is supposed to work? Not sure why this grounded check isn't working..

grim tulip
#

For such things as crouching

slender cargo
grim tulip
#

So cool

slender cargo
#

What im saying, I don't know why the IsGrounded check isn't working

fossil drum
slender cargo
#

I was unaware it comes from the middle

#

That works perfectly, Just increased the value

slender cargo
fossil drum
slender cargo
#

ahh right, that makes sense

#

Thanks Mate!

fossil drum
grim tulip
#

NGL

#

Idk

#

πŸ€·πŸΏβ€β™‚οΈ

#

SORRY

distant current
#

Is there a way in unity to pass a component of an object to another? I'm trying to assign an object that has collider on it and I want that object to be assigned inside one of the objects inside a prefab. So what I did is I created for each, one for a scene and one inside a prefab, I created a script to instantiate the one in a scene.

final crystal
#

How to clear previous debug.drawray ?

faint elk
#

So I have a coroutine that I am using try and make my game wait a frame before continuing to do check. The way I had it explain to me was that in the coroutine i needed to have everything that needed to happen before the wait above the yield return null; and then the game would wait a frame and then run everything after it. After looking at it through a debugger the code runs properly up until the yield statement which instead of pausing for a frame its exiting the coroutine instead of waiting. Does anyone have any idea what I am doing wrong? https://paste.ofcode.org/35D8a7gYttesrfHThbiHFcx

final crystal
#

but I want to see only the ones drawed this frame

fossil drum
#

Well, duration by default is 0 UnityChanThink
So it should clear it if you don't put anything higher then 0.

final crystal
#

mmm, ok

fossil drum
final crystal
#

I see it. I just wanna be sure that the green line wasn't drawed before.

fossil drum
fossil drum
cosmic dagger
faint elk
# cosmic dagger This is a large method. You may want to specify where in the code you have the p...

from how it was explained to me the whole thing should have be a coroutine. The problems is on lines 28 and 51. There is no if statements that would continue execution as this is simple something that gets called to create things and shouldnt return anything. The code after the yield does execute on the next frame, but the problem is that the coroutine is called multiple times in the first frame and then all of them execute the code after the yield on the next one. What I am trying to achieve is having the game stop everything its doing once it hits the yield update the frame and then continue execution because the subsequent runs of the coroutine rely on information generated by the preivous run of it.

rare basin
#

Why it doesn't change the parametr in Animator?

Debug.Log($"Index to set: {indexAnimator}, attack direction: {attackDirection}");
fallAnimator.SetFloat("Fall", indexAnimator);

Animator is referenced, this is the only place in code where im changing this float

faint elk
#

Worth pointing out I do have the execution in a for statement

analog depot
#

is there a way to have unity editor load a specific scene when you hit play? I want to work on my scene, but hitting load runs the 'start' scene instead (to get to my scene fully setup)

willow swift
#

hey gys newbie here can i ask some help on my code ?

fossil drum
gaunt ice
#

just throw your question

fossil drum
#

!code

eternal falconBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

willow swift
#

and that stack overflow thing

swift crag
fossil drum
#

And show the stack overflow error message.

swift crag
#

It should be a pretty simple editor script. It would enter play mode and then immediately load a scene.

swift crag
#

yes, but making that happen isn't exactly obvious -- putting an object in the scene that does it would throw you back to the start screen every time you tried to play the game

#

I think you could add a menu item that starts the game and loads the Start scene

willow swift
#

the line "neighbourTileScript = neighbours[i].GetComponent<scr_TileBehaviour>();" have been pointed out as the problem by unity in the stack overflow message, but sometimes it just crashes

rich adder
gaunt ice
#

next time post your code in the website in !code

eternal falconBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

willow swift
gaunt ice
#

your code may create cycle then stackoverflow

rich adder
willow swift
#

I see

#

sorry

analog depot
swift crag
#

since people usually just screenshot their code editor

#

or is that just how your code editor looks?

#

it looks like a paste site

rich adder
#

yeah looks like gdl

gaunt ice
#

suppose you have two neigbhor tile and they are connected then when you call AltHUD on one of them it calls the other one AltHUD and call back to one, causes cycle

willow swift
#

thats why i used the bools oh i think i get it

cosmic dagger
gaunt ice
#

your guard doesnt block second call on the same instance i think

#
if(called){
  return;
}
called=true
for all neighbors=>call AltHUD
called=false;
willow swift
#

why "called = false;" at the end ?

#

i was gonna make a list of all neighborsthat are already called

gaunt ice
#

just standard DFS, the called=false actually cant be inside the AItHUD method

swift crag
#

The idea would be to mark the tile as being visited already

#

You clear that mark at the end so that the next search can work.

willow swift
#

ok update

#

U made me understand the fact that in a loop it dont read the rest of the code ofc

#

now i dont have the overflow

#

(still dont work lol) Thanks tho

gaunt ice
#
static Stack<instance> path
bool called=false;
public void Method(){
  if(called){
    return;
  }
  called=true;
  path.push(this);
  call neighbors Method()
}
void CallMethod(){
  Method();
  foreach instance in path, reset called;
}
queen adder
#

Hey guys I have this bit of code:

CurrentDay = System.DateTime.UtcNow.ToLocalTime().ToString("dd");

I need the script to just give me the current day, but the issue is that it gets it as a string while I need it as an Int. How can I change this?

gaunt ice
#

int.Parse

solar tide
#

Do you guys have the problem where if you instantiate an object through code and immediately under that code tried to affect the instantiated object's components, that code will not read?
I did encounter this problem and I fixed it by invoking the component affecting method 0.2f second later. I was just wondering if there was a better fix.

swift crag
#

When you Instantiate an object, Awake and OnEnable both run immediately (before Instantiate returns)

solar tide
#

I did all my instantiations on start

swift crag
#

Moving that code into Awake would fix the issue.

#

The rule of thumb is to set yourself up in Awake, and to then talk to other objects in Start (since they will also have had a chance to set themselves up)

#

Alternatively, if you need to do some configuration first, the best option is to write your own "init" method

snow wyvern
#
static Stack<instance> path
bool called=false;
public void Method(){
  if(called){
    return;
  }
  called=true;
  path.push(this);
  call neighbors Method()
}
void CallMethod(){
  Method();
  foreach instance in path, reset called;
}
swift crag
#

and to call that immediately

queen adder
rich adder
rich adder
#

^^

#

easier

swift crag
#

no need to round-trip that through a string

solar tide
swift crag
#

if you did have to use the string, int.Parse would take it and return an integer

swift crag
#

You can then access anything that was created in Awake

willow swift
twin bolt
swift crag
#

materials is a property that returns a new array containing all of the renderer's materials

gaunt ice
#

call CallMethod to start the dfs on each instance, after all instances AItHUD are called then it return from Method, and reset all instance

swift crag
#

Save the array in a variable, update the array, and assign it back to the materials property

rich adder
swift crag
#

That will set all of the renderer's materials.

willow swift
#

yayy, what means DFS ? loop ?

swift crag
#

Depth-First Search

twin bolt
swift crag
#

in a DFS, you immediately recurse on one of your children

#

so it goes all the way down first, before trying the next child

willow swift
#

you guys are the best

swift crag
#

compare this to a Breadth-First Search (BFS), where you check all of your children, then all of their children, and so on and so forth

swift crag
#

I always find BFS more annoying to implement

gaunt ice
#

you can find some animation on youtube of DFS, better to understand

swift crag
#

DFS is dead simple. Check if your current tile is what you want. If not, check each child in sequence

swift crag
gaunt ice
swift crag
#

It does make a copy of the materials the first time you access it, though (and then assign those to the renderer)

#

so that you aren't editing the shared materials

swift crag
#

either would work here

twin bolt
#

okay

swift crag
#

all Renderers have materials

#

Being specific might make your code more clear

#

I got footgunned by this once. I was doing GetComponentInChildren<Renderer> to grab a mesh renderer

#

Then I added a visual effect, and my code (only after a restart!!) started grabbing its renderer instead

#

that took a while to diagnose. it was breaking the visual effect.

willow swift
twin bolt
rich adder
#

active is obsolete

#

use activeSelf

twin bolt
#

@swift crag

brave compass
twin bolt
#

It works now

delicate portal
#

Why is this not working? The first picture's log is working, but then the Action does not invoke.

swift crag
#

Presumably you aren't subscribing to OnNewOfferCreated.

#

Perhaps you're doing it too late.

summer stump
delicate portal
summer stump
#

I dunno, try putting that in awake?

#

Nah wait, do you serialize the reference to emptyPanel? Or capture at runtime?

swift crag
# delicate portal

verify that this is actually running, and that it's referencing the correct emptyPanel

delicate portal
#

emptyPanel is a prefab which is instantiated

swift crag
#

prove that it's the right panel by including this as the second argument to Debug.Log so that you can click the log entry and see where this is

delicate portal
#

You mean like this?

swift crag
#

do this in CreateNewOffer (first image), in Start (last image), and wherefver it is you instantiate the panel

delicate portal
#

Works exactly right

lilac crow
#

Hello good day!
I have a problem with intellisence of vs code can anyone help me?

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

lilac crow
swift crag
#

follow every step to the letter.

wind raptor
#

My GPU usage is consistently at over 90% for an empty scene. I've tried lowering the target frame rate but have noticed no difference. Tips?

swift crag
#

show me a screenshot of your package manager window so I can see if it's configured correctly

#

along with your External Tools settings

delicate portal
#

@swift crag it is about listening to the event I guess. Because in start, I'm listening to a prefab's event

swift crag
swift crag
#

listen to the instance's event

delicate portal
#

okay

#

So?

#

Make a static instance?

soft lotus
#

What does the AABB a error mean?

swift crag
#

Axis-Aligned Bounding Box.

#

It means something is positioned at infinity

#

this can be tricky to nail down.

lilac crow
wind raptor
swift crag
swift crag
#

click the "Stats" button in the game view

#

top right corner

wind raptor
swift crag
#

well, surely you want to listen to a specific panel

#

not just a completely random one

#

Or is this code supposed to listen to all of the panels?

wind raptor
swift crag
analog yew
#

I use this to teleport the Player to a random spawn. I call the coroutine from the start method of my GameManager. However, the player only gets teleported when I start playmode directly from the scene, whenever I enter the scene from my Menu Scene it doesnt teleport the player at all, only the monster. What am I doing wrong?

swift crag
#

well, does the GameManager get created in the menu scene?

delicate portal
#

They have the same script

analog yew
swift crag
swift crag
# delicate portal

perhaps whoever spawns the panels can call a method on whatever this is

distant current
#

can anyone help me how to get a component of an object and pass it to another object?

#

i can't assign the object with component directly in the inspector since I will be assigning inside a prefab

summer stump
distant current
#
using UnityEngine;

public class PassCollider : MonoBehaviour
{
    public GameObject objectB;

    [SerializeField] public PolygonCollider2D polygonCollider;

    public static PassCollider Instance { get; private set; }

    private void Awake()
    {
        Instance = this;
        CopyColliderToOtherObject();
    }

    // Call this function when you want to copy the PolygonCollider2D.
    public void CopyColliderToOtherObject()
    {
        // Get the PolygonCollider2D component from Object A
        polygonCollider = GetComponent<PolygonCollider2D>();

        // Pass the PolygonCollider2D points to Object B
        GetBoundObject objectBScript = objectB.GetComponent<GetBoundObject>();
        if (objectBScript != null)
        {
            objectBScript.polygonColliderB = polygonCollider;
        }
    }
}```
#
using UnityEngine;

public class GetBoundObject : MonoBehaviour
{
    [SerializeField] public PolygonCollider2D polygonColliderB;

    private void Update()
    {
        CopyPolygonCollider();
    }

    // Function to copy the PolygonCollider2D points.
    public void CopyPolygonCollider()
    {
        var sd = PassCollider.Instance;
        polygonColliderB = sd.polygonCollider;
    }
}```
swift crag
#

I have to wonder what happens if you instantiate something with an event

distant current
#

is there something wrong my script?

swift crag
#

Does the event's delegate get copied too?

distant current
#

i need help

buoyant knot
#

i don’t understand what you are trying to do

#

you want gameobject B to get a component on gameobject A?

distant current
#

yes that's right

buoyant knot
#

you can call gameObjectA.GetComponent<>()

polar acorn
buoyant knot
#

you can normally write GetComponent because you are in a monobehaviour class, so the program automatically checks GetComponent in your gameobject

#

GetComponent normally actually calls gameObject.GetComponent

#

but you can call GetComponent on any specific gameobject from any other gameobject

#

idk if that is what is tripping you up

swift crag
#

well, it calls this.GetComponent (which is equivalent to gameObject.GetComponent)

analog yew
polar acorn
analog yew
#

Yes

swift crag
analog yew
swift crag
#

I'm curious about the behavior differing depending on whether you directly started the scene

#

I guess that could affect update order.

polar acorn
# analog yew Yes

Those things don't like to be teleported. They'll ignore movement that comes from other sources. You can add a Physics.SyncTransforms() after teleporting a CharacterController and it'll override their position with the new one from the transform

swift crag
#

Which could make the order between this component and the CharacterController unpredictable

#

That might be it

polar acorn
#

CharacterControllers keep their own internal state, including position, and modify that internal vector, then set the object's transform's position to that every frame. It only reads from the transform when it starts. SyncTransforms tells everything "Hey, read from those transforms again, something's changed" and it updates its internal position

analog yew
#

Oh that's it! I think I fixed it by disabling the CC before teleporting and enabling it afterwards again

distant current
#
using UnityEngine;

public class PassCollider : MonoBehaviour
{
    public GameObject objectB;

    [SerializeField] public PolygonCollider2D polygonCollider;

    public static PassCollider Instance { get; private set; }

    private void Awake()
    {
        Instance = this;

        polygonCollider = GetComponent<PolygonCollider2D>();
    }

}```

```cs
using UnityEngine;

public class GetBoundObject : MonoBehaviour
{
    [SerializeField] public PolygonCollider2D polygonColliderB;

    private void Update()
    {
        CopyPolygonCollider();
    }

    // Function to copy the PolygonCollider2D points.
    public void CopyPolygonCollider()
    {
        var passCollider = PassCollider.Instance;

        polygonColliderB = passCollider.polygonCollider.GetComponent<PolygonCollider2D>();
    }
}```
is this okay now?
polar acorn
analog yew
#

But I still wonder why it worked sometimes before

tiny terrace
#

is there an advantage on using the EnhancedTouch class instead of using InputActions for joystick movement?

polar acorn
swift crag
#

If you have a script that calls Move every frame, the teleporation works if and only if you teleport after that script

distant current
#
using UnityEngine;

public class GetBoundObject : MonoBehaviour
{
    [SerializeField] public PolygonCollider2D polygonColliderB;

    private void Update()
    {
        CopyPolygonCollider();
    }

    // Function to copy the PolygonCollider2D points.
    public void CopyPolygonCollider()
    {
        var passCollider = PassCollider.Instance;
        polygonColliderB = passCollider.polygonCollider;
    }
}```

```cs
using UnityEngine;

public class PassCollider : MonoBehaviour
{
    public GameObject objectB;

    [SerializeField] public PolygonCollider2D polygonCollider;

    public static PassCollider Instance { get; private set; }

    private void Awake()
    {
        Instance = this;
    }

}

is this okay now?

polar acorn
#

If you're gonna use the polygon from the singleton why bother copying it to a variable every frame

#

just use the singleton

#

Also objectB literally does nothing

distant current
#

I want to assign the PassCollider object into Cameramachine Confiner2D but that's inside a prefab object

buoyant knot
#

you just want one gameobject to query another gameobject’s components?

distant current
#

I can't directly assign it since my camera is inside a prefab

polar acorn
#

that's presumably why you made it a singleton

#

so you can use it

#

Just set the variable in the camera to the polygon collider in the singleton

#

You don't need to copy it to a variable every frame

distant current
#

how do I do that?

polar acorn
#

Just... use the variable

#

from the singleton

#

the way you already are

buoyant knot
#

What I normally do is I have EntityDataHolder : Monobehaviour which stores core information for a given gameobject, including its collider and SOs with specific flags about its behaviour.

Then I have EntityAttachmentHandler : Monobehaviour. This monobehaviour goes onto an object that is attached that keeps as a field a reference to the gameobject to which it is attached.

polar acorn
#

but do what you actually want with it instead of storing it in a variable

#

Just delete polygonColliderB and use PassCollider.Instance.polygonCollider when you need to use it

distant current
#

Im sorry for asking much, Im new to unity so I dont have much knowledge

#

ohh let me do that

#
using UnityEngine;

public class PassCollider : MonoBehaviour
{
    public GameObject objectA;

    [SerializeField] public PolygonCollider2D polygonCollider;

    public static PassCollider Instance { get; private set; }

    private void Awake()
    {
        Instance = this;
    }

}```
```cs
using UnityEngine;

public class GetBoundObject : MonoBehaviour
{
    [SerializeField] public PolygonCollider2D polygonColliderB;

    private void Update()
    {
        var passCollider = PassCollider.Instance;
        if (passCollider != null)
        {
            if (polygonColliderB != null)
            {
                Destroy(polygonColliderB);
            }
            polygonColliderB = passCollider.polygonCollider;

        }
    }
}

is this it?

#

it destroys the component of objectB but it doesn't use objectA's component

polar acorn
#

Literally just get rid of polygonColliderB

#

that variable does not need to exist

#

It's completely pointless

gaunt ice
#

it will destroy the instance polygoncollider....

#

btw why you do it on update, or i miss some chats

polar acorn
distant current
#

what will i use as a parameter of my polygonColliderB?

#

just the object itself?

polar acorn
#

polygonColliderB does not need to exist

#

Just remove the variable and all uses and references to it

#

and use the polygonCollider from PassCollider instead

buoyant knot
#

and why is it a polygoncollider2D, and not a collider2D?

polar acorn
#

That's the least of the problems with this setup

buoyant knot
#

yeah, I think his class should be very simple

distant current
#
using UnityEngine;

public class PassCollider : MonoBehaviour
{
    public GameObject objectB;

    [SerializeField] public PolygonCollider2D polygonCollider;

    public static PassCollider Instance { get; private set; }

    private void Awake()
    {
        Instance = this;
    }

}```

```cs
using Unity.VisualScripting;
using UnityEngine;

public class GetBoundObject : MonoBehaviour
{

    private void Awake()
    {
        PassCollider.Instance.polygonCollider.GetComponent<PolygonCollider2D>();
    }
}

is this it?

buoyant knot
#

wait, is the whole goal here to get a collider into a singleton?

polar acorn
#

And why are you getting a polygon collider and doing nothing with it

#

and why does this class even exist

buoyant knot
#

all of these questions

distant current
#

I just want to pass the component of an object to another object

buoyant knot
#

this whole class would just be holding one collider, right? and give you global access to that one collider?

#

this is not the way to do this

distant current
#

will you help me?

polar acorn
#

GetBoundObject seems to be completely pointless. You have the collider from PassCollider. It's accessible everywhere. That's why you made it a singleton

#

Just use that

buoyant knot
#

you are trying to make a singleton, which is a class of which there is only one instance

#

so you can only hold ONE collider, because there is only ONE instance of the singleton

#

but why do you even want that one collider to be accessible from everywhere?

distant current
#

I meant I want to assign that object that has PassCollider script attached on it into an inspector of one object inside a prefab

buoyant knot
#

i think we need to back up several steps

#

there are several layers of doing things wrong that we need to unpack here

distant current
#

Im so creating two object, one from the scene and one inside a prefab

polar acorn
buoyant knot
#

bro

polar acorn
buoyant knot
#

you need to know how references work

#

that’s like, programming 101

#

this is like trying to learn how to read without knowing the symbols used in the language

distant current
#

alright, i will figure it out myself

buoyant knot
#

you mean you will read the link that tells you how it works?

polar acorn
buoyant knot
#

one of these days, the next time someone doesn’t read a link that clearly answers their question, I’m just going to start copy pasting the text in that link bit by bit into discord

stark ruin
#

Hi guys,i need to build a game on standalone and i need to see the errors in the console log,how can i print them inside the game?

summer stump
stark ruin
#

Cause it is what i am trying to do

polar acorn
stark ruin
#

Thanks

swift crag
#

Oh shoot

#

That's really useful.

final kestrel
#

https://hatebin.com/pnscqbdeof
The script is to change the glow when pointer enters. It all works fine till I press play and start the game. Then When I come back to main menu. Even though im not hovering over the last pushed button which is play. It still is glowing until I hover over and trigger pointer exit again. Anyone know why?

polar acorn
#

Disabled objects stop all coroutines, so it doesn't finish its fade thing. You should probably have an OnDisable that instantly resets the glow back to normal with no timer

final kestrel
#

Hmm all right thanks.

#

Ahh I also need OnEnable too?

#

Can I just stuff them into my current script? Or could it be cleaner

#

Ahh I got it work. Thanks digiholic

rocky canyon
#

so unreal has this variant manager.. its cool for things like day / night presets.. (as i build materials i like to switch around)
my question is how would be the best way to go about replicating something like this? (not including the drag and drop preset stuff)

i think i would use Scriptable Objects, and a class with a slot.. then i can loop thru the components and set them according to what SO i have assigned..

#

i could just use an editor function to swap in edit mode..
i'll give that a shot first and see how it works out

autumn bough
#

Hello! I was wondering if anyone could point me to good resources about how to use the unity profiler (or some other thing!) in order to identify memory leaks / garbage collection issues and then pinpoint their location in my codebase?

rocky canyon
#

medium always has good articles to get u started.. / familiarize urself with

autumn bough
#

TYTY!

rocky canyon
#
  • look for spike
  • click the spike
  • expand the call logs
  • find the class / loop taking the most time to run
merry nebula
#

Hey everyone, I am expiriencing a pretty weird issue where my collision doesn't work at all, basically I don't know what mistake exactly I'm making, or if I'm even being crazy, but if 2 objects who just have their own colliders get in contact they should collide somehow, even just crashing if one runs into the other, and mine just kinda ignore each other. Now the thing is that they the obstacle can kill my player on touch with it because of the script i used, but they never collide if i take out the script, so it's kinda as if collider is there but he doesn't work at all. I will gladly provide screenshots or videos if needed, if anyone is willing to help πŸ™‚

languid spire
merry nebula
#

Just a moment

#

First 2 are for player

summer stump
merry nebula
summer stump
merry nebula
#

Yes

summer stump
#

Both must have it deselected.

merry nebula
#

But then how will it react to my OnEnterTrigger2D() btw?

summer stump
#

Ok, so, what layer is the player on, and have you touched the collision matrix?

keen dew
#

Does any of those have a rigidbody?

summer stump
summer stump
languid spire
#

OnEnterTrigger2D ??

summer stump
#

Oh yeah, that isn't what it's called btw. Just the enter and trigger part reversed

merry nebula
merry nebula
#

To see it

#

And I am also kinda shocked to realise am supposed to just not do it? Even tho it worked yesterday?

#

Idk I feel like there is a bigger issue to it, or just something i am missing out

summer stump
#

Something else caused it to collide. Triggers do not

You had a different setup if it worked

violet topaz
#
public class Shoot : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;

    public float bulletForce = 20f;
    public float timeBetweenShots = 1f;
    // Add Max ammo, reload, mag size

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButton("Fire1"))
        {
            Shooting();
        }
    }

    public void Shooting()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        rb.AddForce(firePoint.up * bulletForce * timeBetweenShots, ForceMode2D.Impulse);

    }
}``` can someone help me make multiple bullets spawn in each other
summer stump
#

Like I said though, just use two colliders. One non-trigger to collide.
One a trigger that is slightly bigger if you want to get that OnTriggerEnter

Or just use OnCollisionEnter

merry nebula
summer stump
#

That is common for doing a "sight range"

summer stump
violet topaz
#

oops my bad

trim cedar
#

if anyone has knowledge about using color in scrpits, help would be apprichiated. heres my code:

foreach (SpriteRenderer pumpkin in pumpkinSprites)
  {
    pumpkin.color = Color.HSVToRGB(0f, 0f, 10f);
  }

and here is what it actually does (the V value previously being 100f):

#

No matter what value i enter for V in the script, it always just makes it 75 and i have no idea why

trim cedar
#

ah, that makes sense, thank you

edgy prism
#

This is probably a stupid question so apologies in advance but within my scripts I have a Dialog Manager and an NPC Controller doing what they say on the tin. Now my Dialog Manager is just a singleton with different methods to call different types of dialog however I want to add Character Sprites and names to my dialog window and Im not sure whether to do this in my NPC Controller (the option im leaning towards) and then doing so independent of the Dialog System or somehow try and get a reference in the Dialog Manager to what called the dialog and if its an NPC to set an image sprite and a name sprite

rich adder
edgy prism
rich adder
wintry quarry
edgy prism
#

I do not, so far Ive just been trying to figure out the best way to do it

wintry quarry
#

the type of which is your ScriptableObject for a character or whatever

#

the character object should have:

  • name
  • speech color?
  • maybe a font?
  • portrait sprite
  • whatever else you want
rich adder
#

yea SO for each character would be perfect

edgy prism
wintry quarry
#

You will want to have some kind of class that describes a character

#

it doesn't have to be a ScriptableObject

#

though they are pretty convenient for this.

edgy prism
#

See this is why I thought it a stupid question because I have a character class that right now just handles movement and things like a LookTowards function, My NPC Controller that I mentioned opens dialog on Interact and I just dont really know where best to put all this stuff

wintry quarry
#

I'm thinking of something more like an object that holds all of the necessary info to describe one of your story characters.

#

I would not combine those

#

If you don't have such a thing already, I recommend creating it.

uncut dune
#

how do I get an int of a float without rouding the values

#

just using the first digits before decimal

edgy prism
wintry quarry
#
int myInt = (int)myFloat;```
uncut dune
#

like

#

15.6 = 15

wintry quarry
#

it truncates

#

yes like that

buoyant knot
uncut dune
#

thank you

wintry quarry
# uncut dune ok

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions#explicit-numeric-conversions

When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value. If the resulting integral value is outside the range of the destination type, the result depends on the overflow-checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.

edgy prism
#

Ive just managed to confuse myself with the scope of everything, I never thought id have so much going on it would be hard to keep track of πŸ˜†

#

Would it be a better idea to create SO's and reference them in my class over just creating fields in my class and setting them in the inspector?

muted wadi
#

im trying to implement a 3rd person camera into my game without the use of cinemachine and have it almost done, I just can't figure out why the camera isn't clamping.

{
    float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
    float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
    horizontal = Mathf.Clamp(horizontal, -90, 90);
    lookAt.transform.Rotate(vertical, horizontal, 0);

    float desiredAngleY = lookAt.transform.eulerAngles.y;
    float desiredAngleX = lookAt.transform.eulerAngles.x;
    Quaternion rotation = Quaternion.Euler(-desiredAngleX, desiredAngleY, 0);
    transform.position = lookAt.transform.position - (rotation * offset);

    transform.LookAt(lookAt.transform);
}```
rich adder
dry tendon
#

heey, does someone know why the print works but the var doesnt get false? ```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PipesCollision : MonoBehaviour
{
public bool hasCollisioned;

private void Start()
{
    hasCollisioned = false;
}

//Check collision with player
private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.tag == "Player")
    {
        hasCollisioned = true;
        print("Te has chocado");
    }
}

}```

rich adder
#

ideally you don't want this mixed with your Locomotion script etc.

eternal falconBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

rich adder
#

bit strange

cosmic dagger
muted wadi
edgy prism
muted wadi
#

also i did try clamping the desiredAngleX but that didn't work

rich adder
edgy prism
cosmic dagger
dry tendon
#

sorry, i meant why it doesnt get true on the trigger

cosmic dagger
#

after the console prints, show is the variable from the inspector . . .

rich adder
#

it should tbh be something different like public class CharacterInfo or something

summer stump
edgy prism
dry tendon
polar acorn
#

How do you know it's not

summer stump
edgy prism
rich adder
#

and keep it separate from other logic/code

#

you don't want a monolith class full of fields

#

eg mixing movement / stats with other datainfo meant mainly for visuals

dry tendon
polar acorn
edgy prism
polar acorn
#

Or something else is changing the variable after it's set to true

dry tendon
dry tendon
#

it gets true on the object

#

not in the prefab

polar acorn
#

Of course it isn't set on the prefab

summer stump
polar acorn
#

the prefab has not collided with anything

dry tendon
#

cause the game is instantiating that prefab... so i need to change that in all instantiated objects

#

how could i do that?

polar acorn
#

it has no connection to it

#

If you don't want each individual instance of this script to have its own copy of the variable it probably shouldn't be on this class

dry tendon
#

oh, thanks... ill look for another way to do what i want

grim tulip
#

IM BACK FROL SCHOOL

#

finally

#

Time to learn to code

#

YAY

muted wadi
#

could someone explain to me what variable I'm supposed to be clamping on a 3rd person camera? Someone said I shouldn't be clamping the input values and that makes sense. But I'm still not sure which value exactly I should be clamping.

summer stump
summer stump
rich adder
muted wadi
# rich adder are you doing rotation? you would clamp the rotation ideally

this is what im working with right now, and I've tried clamping the rotation, but it doesn't work and i dont understand why

    inputX = Input.GetAxis("Mouse X") * rotateSpeed;
    inputY = Input.GetAxis("Mouse Y") * rotateSpeed;
    lookAt.transform.Rotate(inputY, inputX, 0);

    desiredAngleY = lookAt.transform.eulerAngles.y;
    desiredAngleX = lookAt.transform.eulerAngles.x;
    rotation = Quaternion.Euler(-desiredAngleX, desiredAngleY, 0);
    transform.position = lookAt.transform.position - (rotation * offset);

    transform.LookAt(lookAt.transform);
}```
muted wadi
summer stump
#

You're calling LookAt after all that rotation setting...
Oh wait. You're setting the rotation OF lookAt... ok

rich adder
#

rewriting camera script when you have cinemachine, is like re-inventing the wheel

slender nymph
muted wadi
muted wadi
slender nymph
#

search "clamp camera" in this discord for many examples

late burrow
#

if i run string.replace but string is not found does it still gets the string that would be used as replacement?

eternal needle
late burrow
#

ok more exactly

#

will script error out if string used as replacement will be from invalid index of array

#

if string to replace was not found at all

cosmic dagger
late burrow
#

yeah i dont know if second part is executed or no

cosmic dagger
late burrow
#

i know it returns original string

cosmic dagger
#

there's no need to check newChar if the first part is false . . .

late burrow
#

but does script errors out if it has errorprone code in newchar

cosmic dagger
#

that's just my guess, you'd have to test it . . .

eternal needle
#

or a char

late burrow
#

array[-1]

eternal needle
#

yes that'll be an error..

languid spire
#

the string replace will not throw an error because Array will beat it to it

gaunt swan
#

If you want the last element you need array[^1]

late burrow
#

dont know what is even this operator but very useful

gaunt swan
#

I assume you are a python programmer πŸ˜…

lilac crow
languid spire
#

which can still throw an error

late burrow
#

yes that was the point of question

gaunt swan
#

Yep, but -1 will never be valid

late burrow
#

array can be empty but i will be replacing using array

late burrow
#

but if found then it always be valid

late burrow
#

usually you start array from 0

#

but when ^ then from 1

gaunt swan
#

It takes length-value

#

length is outside of the array

#

The compiler uses System.Index which is passed to the array

#

var lastItem = array[^1]; // array[new Index(1, fromEnd: true)]

slender nymph
#

although if you're still making stuff for vr chat you can't use that since vr chat uses unity 2019 which does not even support c# 8 where that operator was introduced

#

i'm pretty sure you have to be targeting .net standard 2.1 to use it at all. i could be wrong about this and it may work on 2021+ when targeting .net framework but it does not work on 2020 and below

swift crag
#

The instructions tell you to update the Visual Studio Editor package to 2.0.20 or later

#

you will need to remove the "Engineering" feature to unlock the package, then re-install it

lilac crow
#

you saved me!!!!!

#

i was going crazy.

fickle knoll
#

i need some help. im making my first game and i have made a platform with a car on it and some obstacles. But my car just drives thought the stuff also all the things just fall down, ive tried ading a ridgidbody but it dosent work

gaunt swan
fickle knoll
#

yea prob

#

how to add

gaunt swan
#

Add either a collider2d or collider3d, depending on what you are doing

fickle knoll
#

okay

gaunt swan
#

e.g. a BoxCollider

polar acorn
fickle knoll
#

now things arnt falling down but i cant drive up things like rams i just drive through them

#

hello

polar acorn
#

How are you moving your player

fickle knoll
#

wasd

#

you want to see the code?

#

ik big brain

slender nymph
#

typically when people ask how you are moving an object, they are not referring to the buttons you press but rather how you actually move it in your code

fickle knoll
slender nymph
#

!code πŸ‘‡

eternal falconBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

slender nymph
#

also your !IDE is not configured

eternal falconBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

fickle knoll
#

i've tried that

#

dosent wrok

#

work

slender nymph
#

a configured IDE is required to get help here

fickle knoll
#

can you help me configure it

slender nymph
#

follow the instructions

fickle knoll
#

ive tried

#

dont work

rich adder
fickle knoll
#

to configure my ide

rich adder
#

how did you do it?

slender nymph
# fickle knoll dont work

if the instructions don't work, then you've either skipped something or followed the wrong instructions. because spoilers: ||they do work||

fickle knoll
#

dude ive tried like 5 times

pearl coyote
#

But what exactly

fickle knoll
#

the guide

rich adder
#

which guide / which code editor

#

say useful answers, we're not here to play 20 question if you want help

fickle knoll
#

by code editor you talking about visuial studio or vs code?

pearl coyote
#

You are using Visual Studio