#archived-code-general

1 messages · Page 421 of 1

leaden ice
#

furthermore:

    bulletInstance.AddComponent<Rigidbody2D>();
    bulletInstance.GetComponent<Rigidbody2D>().AddForce(...);```
is also silly.
Do this:
```cs
Rigidbody2D rb = bulletInstance.AddComponent<Rigidbody2D>();
rb.AddForce(...);```
#

better yet - just add the Rigidbody directly on the prefab instead of adding it in code.

vague cosmos
#

Also makes sense, let me change those real quick

#

Vector3 offset = new Vector3(this.transform.position.x -0.5f, this.transform.position.y, this.transform.position.z);

GameObject bulletInstance = Instantiate(lrSpecialBullet, offset, Quaternion.identity);

I added an offset vector and changed the instantiate line to this, but now the projectile never instantaites at all for some reason

dusk apex
#

Maybe place a log and see if those lines were executed

vague cosmos
#

The lines were executed, I did check that. It's likely im just using instantaite wrong, i'm just not sure what the issue is

dusk apex
#

It wouldn't instantiate the object if the lines aren't called. Other than that, the object would be missing from the hierarchy if the object was destroyed.

leaden ice
vague cosmos
#

Yeah, the code runs but there is no object in the hierarchy

leaden ice
#

again have you actually checked what offset is defined in the prefab itself?

leaden ice
#

you probably have code that destroys it when it collides with something

vague cosmos
#

Oh yeah i do, let me actually stop that rq

#

Also, you were correct there was an offset in the prefab

leaden ice
#

set it to 0

#

As a general rule of thumb prefab roots should always have 0,0,0 transform

vague cosmos
#

Yeah, that makes sense

#

Still, the right works and the left does not, even turning off the destroy code

leaden ice
#

In what way does it not work

vague cosmos
#

One second

dusk apex
#

Can you show the console logs?

vague cosmos
dusk apex
#

And the edited code

vague cosmos
wheat spruce
vague cosmos
leaden ice
#

He's not using an Instantiate form that sets the position

wheat spruce
#

it does sound right for it to be instanced in whatever the roots position was, say I had a cloud prefab that I want to be at 0,100,0, I could simply instance it at 0,0,0 and I know the cloud will actually be spawned at 0,100,0

high trellis
#

any help would be great! :) i have an issue where keep getting the error that the object reference it not set to an instance of an object and im not too sure where im going wrong, public class Weapon : MonoBehaviour
{
private InputManager controls;
private Camera cam;
private RaycastHit rayHit;

[SerializeField] private float bulletRange;
private bool isShooting;

private void Awake()
{
    controls = GetComponent<InputManager>(); // im getting the error code here when i run the game but im not entirely sure whats causing it 
    cam = Camera.main;

    controls.onFoot.Shoot.started += ctx => StartShot();

}
leaden ice
#

show the actual full error message

tawny elkBOT
leaden ice
#

and the full script(s)

vague cosmos
#

So i figured it out
I just had to increase the offset

#

Thanks for the help, sorry for making that more trouble thatn it needed to be

high trellis
wheat spruce
naive swallow
high trellis
#

controls.onFoot.Shoot.started += ctx => StartShot();

somber nacelle
#

the only line in Awake that could throw is the last one

leaden ice
high trellis
#

thats line 19

naive swallow
somber nacelle
#

and this means that controls is likely null because there is no InputManager component attached

rigid island
#

you never initialize your controls
nvm InputManager seems to be component not input c# class

leaden ice
#

or one of the fields in that chain is null

#

Actually it may be more likely to be that - and probably a race condition with the different Awake functions

naive swallow
#

So either controls, controls.onFoot, or controls.onFoot.Shoot is null

wheat spruce
#

whatever game object has the component thats giving the errror, does not also have the InputManager component attached

#
controls = GetComponent<InputManager>();
Debug.Log(controls);```if the log produces an error, thats a very straight forward problem
somber nacelle
#

that log wouldn't produce an error either. but it could print null

high trellis
dusk apex
high trellis
#

thats the full script

wheat spruce
#

oooh right of course

dusk apex
#

NRE only occurs if you're attempting to access a member from a null reference

rigid island
#

ohh it is custom class?

#

you need controls.Enable()

wheat spruce
#

to be fair im in the middle of cooking so its hard to think 😅

leaden ice
#

It doesn't manke sense that we're doing new InputManager() in one script and GetComponent<InputManager> in another

#

something is wrong

rigid island
#

this confusing af

high trellis
#

i tried a different method but ended up with the same error the one i posted is the original one i was working on my bad

rigid island
#

lets see what InputManager is ?

high trellis
#

i think its something to do with that i completely forgot about that script

rigid island
#

nest keeps getting worse

rigid island
wheat spruce
#

make sure to dice the onions to add to the spaghetti

#

it makes the code tastier

rigid island
#

mama cried but it wasn't onions

high trellis
#

unity player input

rigid island
#

well its a component you should not be new it

rigid island
dusk apex
#

A picture would suffice since it isn't a script

rigid island
#

PlayerInput doesn't have type safety no? you wouldn't be able to see any of the actions without string

#

could be classic mistake of naming something the same as unity component

rare thorn
#

My Unity has to Reload Domain every time i change some code. Is there a way to only make it compile when i press play?

rigid island
#

and that would be for all assets

somber nacelle
high trellis
#

thats the input system action map, unless you want the generated script?

somber nacelle
rigid island
#

and called it playerInput ?

high trellis
rigid island
#

ok so new() would be correct..

#

the name is just bad cause confuses with unity Component PlayerInput (also horrible name)

high trellis
rigid island
somber nacelle
tawny elkBOT
#

:teacher: Unity Learn ↗

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

somber nacelle
rigid island
#

I think its missing for the original script though no?

#

Weapon.cs

somber nacelle
#

that is calling GetComponent for the InputManager component

#

which is the component that instantiates the PlayerInput object

#

their WeaponManager component is erroneously instantiating InputManager though when it should be using GetComponent

rigid island
#

OH thats InputManager

#

myb mb

#

this is mixing 2 different inputs ways lol confused me

magic tusk
sterile echo
#

serializefield variable vs getcomponent in start, which is more optimized? and WHY!

rigid island
#

dependency injected vs runtime lookup

#

have a start with 7-8 GetComponents x 100 enemies, see how efficient that is for Start to run

modern creek
# magic tusk

You want to look up content size fitters - unfortunately the solution isn't super trivial, but it's not impossible. Basically you need to know that content size fitters will fit content after the current tick - so if you're trying to get the rect transform size, you'll need to wait a tick until the CSF and layout group have had a tick to repaint themselves

magic tusk
#

It was not intuitive at all but I believe what happened was that when I put content size fitter on the very outermost element the content size fitter magic trickles down to the individual child, so I just made my textbox prefab as if it had a content size fitter and then it seemed to work

modern creek
#

I wrote some code a couple years ago that will do something else you might find useful - sets a GO to the "minimum" size based on the nested content - useful if you have nested CSFs like that.. lemme see if I can dig it up and paste it.. No idea what state it's in but you might look over it and find something useful

#

This code is at least a year old - but I think most of my codebases still use this to set things vertically to the smallest amount.. just be careful since it won't work for disabled GOs (the CSFs don't do anything while disabled) or not yet Awake'd - ie, you can't do it in the same tick as when you instantiate - hence the wait one tick coroutine at the top

magic tusk
#

ty

wheat spruce
#

I am stunned that such a thing is not built in behaviour for the layout groups

#

Though, I cant speak for the new UI system

#

The way they currently work, you know all theyre doing is just divide the length by number of rows/cols + padding

#

majority of use cases this is enough, so its not too much of an issue

karmic stone
#

how do i extend customEditor to make it work above an item (such as [Textfield("EditorText")] above a string). Like how you use [HideInInspector]

wheat spruce
#

🤔

karmic stone
#

thank you osmal, i didnt think of propertyAttributes

wheat spruce
#

I've also wondered about this, but hadnt looked into it before now. https://github.com/dbrizov/NaughtyAttributes I poked around in here to see how they implemented their [button] attribute, and I noticed that derives from Attribute not PropertyAttribute, yet other classes use the latter

#

I cant seem to spot the source for Attribute in that repo, or in the docs

leaden ice
wheat spruce
#

ah!

leaden ice
#

PropertyAttribute derives from Attribute

#

It's what lets you make an [Attribute]

wheat spruce
wheat spruce
heady iris
#

The content size fitter resizes its own RectTransform based on how much space it wants

heady iris
#

more specifically, you shouldn't have a fitter controlling a direction if the parent has a layout group controlling the same direction

#

Doing this is objectively wrong, and it results in all of this weird hackery

#

If your parent controls your size, then your parent will give you enough space -- as long as you ask for it

summer hazel
#

looking for some clarity on some stuff since there's a lot of mixed info online.
does anyone have resources/hints on what I should be using to mix the following:

  • unity UI (w/ canvas and so on)
  • mouse events on gameobjects, but not through the UI
  • the new input system

so far I've seen posts/articles/etc. that either ignore interaction between one or more of these, claim certain approaches are more or less deprecated, claim some are poorly (or barely) supported by Unity in some unfinished state, etc.

just kinda baffling that something so simple doesn't really seem to have a straightforward approach, at least that I've found so far, so any nudges in the right direction would be appreciated lmao

heady iris
#

So this is something I only figured out like

#

a week ago

#

the Event System is, by default, only used to interact with graphics

#

via the Graphic Raycaster

#

however, you can use it for things with colliders too

#

using the Physics Raycaster

#

So you can add event handlers to game objects with colliders, and they'll only receive click events if the UI isn't in the way

#

I believe you just need to slap a Physics Raycaster onto the object with the camera

latent latch
#

Most UI events also sort on hierarchy for when that raycast is blocked, so you will always be blocked by the most priority

#

otherwise manual graphic raycasting is basically a raycastall

#

Makes sense though, how do you know what's being blocked if everything is occupying the same z space?

heady iris
#

yes, UI uses different rules

heady iris
#

it's one big unified system

#

I've been using EventSystem.IsPointerOverGameObject() to check if my cursor is on top of UI before doing a physics raycast to look for an object

summer hazel
heady iris
#

That has nothing to do with the event system

#

I'm also pretty sure they only work with the old input manager, but I have not tested that.

summer hazel
#

yeah that's kinda my issue lmfao, it seems like nothing is designed to work with other parts of the engine on a fundamental level

#

so I'll need to instead set up manual raycasts and handle the events from that within the camera, then?

heady iris
#

No.

#

you add a Physics Raycaster to the main camera, then add components that implement the various event methods to the target objects

#

When you click, the Event System will test for both UI and non-UI objects

#

it'll hit Graphics (in your UI) and Colliders (elsewhere)

rare oasis
#

hey this is my first time using unity for an assignment and my player object is supposed to collect the coin but instead it's just phasing through all of the coins even though the colliders are there. Does anyone know what the issue may be. (first ss is the for the coin object thats supposed to be collected/destroyed, the last two are for the player object)

summer hazel
heady iris
#

you don't shoot raycasts at the UI, do you? (:

summer hazel
# heady iris you don't shoot raycasts at the UI, do you? (:

I mean, no, but I also wouldn't expect it to be considered a raycast in the first place I guess - or that if it is, that while parented to a camera that it wouldn't like... default to just extending toward the camera's facing angle, without the destination point moving with the mouse. kinda a bit of a misnomer on their part imo since it's more of a mouse input handler built on top of a raycast component.

but uh... upon testing, it seems it doesn't work. could be I missed a step - currently have the Physics Raycaster on my camera, the object (with collider) implements the necessary interfaces, but no input captured. UI still works though- oh wait. would the canvas prevent input from being passed behind?

#

if that's the case I assume I'll have to mask that in the raycast but idk if there's a better approach

heady iris
#

However, if anything in your UI is blocking the raycast, it won't reach the object

#

This could include non-visible objects

summer hazel
#

turns out it wasn't the canvas after all, I removed it completely and still no input captured on the gameobjects

heady iris
#

You do have an Event System in the scene, right?

summer hazel
#

yup!

heady iris
#

and the Physics Raycaster is attached to an object with a Camera component (not a Cinemachine Camera, perhaps)

summer hazel
#

yeah, just a default camera object from a brand new project scene

heady iris
#

that's what I used

summer hazel
#

yeah, in my case I used IPointerEnterHandler and IPointerExitHandler, but I would assume they work as you'd expect

heady iris
#

If you turn your UI back on, can you click on buttons?

summer hazel
#

yeah.

heady iris
#

so your scene currently contains:

  • a cube (or some similar object), with:
    • a collider
    • your component
  • a canvas (deactivated)
  • an event system
summer hazel
#

yup, precisely that. and the camera with the physics raycaster.

#

the collider is a 2D (circle) but I wouldn't imagine that would make a difference, since it worked with the previous methods

#

(e.g. OnMouseEnter)

heady iris
#

Oh

#

you need a Physics2D Raycaster then

latent latch
summer hazel
summer hazel
#

aight. thanks

heady iris
#

But I also haven't used them much before

summer hazel
#

yeah that worked. hopefully nothing explodes! thanks for the help.

elfin tree
#

if I have a scriptable object that has a [Serializable] object instance as a field, can I straight up use it and modify it, or should I make a copy first?

leaden ice
#

Why wouldn't you be able to use and modify it

#

It will get modified on the asset in the editor though

#

If that's what you mean

dusky lake
quiet loom
#

if (Input.GetKeyDown(KeyCode.E))
{
RaycastHit2D hit = Physics2D.Raycast(
origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
direction: Vector2.zero,
distance: Mathf.Infinity
);

        if (hit.collider != null)
        {
            rope.enabled = true;

            grapplepoint = hit.point;
            grapplepoint.z = 0;
            joint.connectedAnchor = grapplepoint;
            joint.enabled = true;
            joint.distance = grapplelength;

            rope.SetPosition(0, grapplepoint);
            rope.SetPosition(1, transform.position);
        }
    }
    if (Input.GetKeyUp(KeyCode.E))
    {
        rope.enabled = false;
        joint.enabled = false;
    }
    if (rope.enabled == true)
    {
        rope.SetPosition(1, transform.position);

    }

this code is designed for a grappling hook but when it runs the player loses all momentum at the bottom and barely moves whatsoever, can someone help?

fleet gorge
quiet loom
#

shouldn't it preserve the velocity though? and how would i fix the raycast

leaden ice
# quiet loom if (Input.GetKeyDown(KeyCode.E)) { RaycastHit2D hit = Physic...
RaycastHit2D hit = Physics2D.Raycast(
                origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
                direction: Vector2.zero,
                distance: Mathf.Infinity
                );```
If you want to do a mouse raycast in a single point to 2d objects, you shoould be using https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics2D.GetRayIntersection.html. with Camera.ScreenPointToRay
quiet loom
#

he also like stops being affected by gravity when basically horizontal

#

is a layermask required btw

fleet gorge
#

not really, but depending on the function's override they might make you use it

leaden ice
quiet loom
#

so the frog basically starts moving really really slowly along the circumference of the circle that would be traced out by the distancejoint at around this point

#

would switching to rayintersections and camera screepoint to ray fix taht

leaden ice
#

no

#

that's clearly a problem with your physics

cyan dew
#

when i modify scriptableobject data during runtime, the changes save - is this the correct approach to fix the issue or will i run into bigger problems down the line cause of it?

quartz folio
#

That is fine. Though generally it's easiest to treat SOs as immutable and to create a runtime instance of the data that's modified

cyan dew
#

ahh i see

#

ty ty ❤️

pliant trout
#

hello i started to learn programming in unity and once i learned the basics i dont know what to type in the programming scirpt i have ideas but i dont know how to type you know theres errors and stuff.

pliant trout
leaden ice
#

Could you try to rephrase it? Because I didn't see a question in there.

pliant trout
#

but i dont know what to do once i start to program my self

heady iris
#

to be frank: you haven't learned the basics, then

#

it's common for people to over-estimate how much they understand when they're starting out

#

I heard this quite a bit from students when TAing

leaden ice
#

I also still don't really see a question here

heady iris
#

nothing wrong with being a novice -- you just need some more time (:

leaden ice
#

but yeah it's going to take you at least a year before you comfortably "know the basics" of programming

heady iris
#

and you really just have to do more

#

the Unity Learn pathways have a lot of material to go through

heady iris
#

repetition will get you more familiar with this stuff

pliant trout
#

do you have any tips or courses that you think will benefits me

main stirrup
#

So I want my player to not fall though platforms that are moving fast which, of all things, seems like something kinda simple, but...I'm just not exactly sure what a reliable solution would be for that. I'm using a raycast to check if the player is on the ground btw

dusk apex
#

A simple raycast downwards and teleporting using Transform?

#

If you're using Rigidbody, try setting the simulation to continuous

main stirrup
#

oh yeah..I guess I didn't really make it so that the player actually sticks to the platform..

#

I only made it so they can jump if they were on ground

vestal arch
#

yeah that or use physics to do collision

main stirrup
#

and then...there's also horizontal platforms... Guess I'll just do that when it becomes an actual problem

vestal arch
#

what are you using for movement?

main stirrup
#

rigidbody physics

#

just setting the velocity

vestal arch
#

you could probably just have platforms move stuff on top of them with movetowards

#

or maybe set a friction

#

or maybe parent them

#

there's a lot of ways

dusk apex
#

If you do not want to parent the object, consider using a parent constraint component.

latent latch
#

Really wish some of the constraint stuff were just gameobject properties

#

lot of times I just want to child something and prevent rotation

sterile reef
latent latch
#

yeah im saying feels bloated to do that

#

like near the transform values should just give us constraints

sterile reef
#

I mean... is it possible to extended the Transform class?

vestal arch
#

yeah, like RectTransform

#

idk if you can like, replace the transform of an existing game object though

sterile reef
#

Oh wait

#

You can just create an editor script

#

For Transforms

latent latch
#

oh and SCALE

sterile reef
#

All my homies forgetting scale

reef blaze
#

I'm generating a level at the start of a scene. Should this be done with a coroutine instead? The first frame of the scene can take a long time. Is using a coroutine faster? Is it bad practice to overload the CPU with a long Start function? I'm assuming yes. Maybe this is a dumb question.

dusk apex
thick terrace
#

but using a coroutine lets you do stuff like show a progress spinner, so if it's a really long load maybe you need that

reef blaze
#

holy f bros. I did not realize you could use yield return in a for loops like this

steady bobcat
#

cus it would shit on performance to have alternate processing for transformations

barren patio
#

maybe my question is more suited here, how does one DRAW a mesh from a matrix of chunks efficiently, the generation is no issue but the second i have to render it takes very long to make the mesh due to checking through every block to see if their is neighbors touching. so how do i go about it?

maiden fractal
craggy veldt
reef blaze
#

I didn't know you could have yield return in a for loop in general! 😮

reef blaze
# craggy veldt like what? super curious 🤤
{

    bool isSpawned = false;
    while (isSpawned == false)
    {
        Vector3 randomPos = RandomPointInBounds(pos, maxPos);
        if (SpawnLargePrefabRandomly(GenerationManager.instance.GetRandomBuilding(), randomPos))
        {
            yield return new WaitForFixedUpdate();
            isSpawned = true;
            
        }


    }

}```
#

im gonna do so much stuff in coroutines now

fiery gate
#

!vc

tawny elkBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

frail knot
#

i dont get an error also, cause when i press play it doesnt follow the player? love if someone helps me (need i to change something in this script? using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
using Unity.Cinemachine; // Vergeet niet de Cinemachine namespace toe te voegen

public class PlayerManager : MonoBehaviour
{
public static bool isGameOver;
public GameObject gameOverScreen;
public static PlayerManager instance; // Singleton instance

public static int numberofCoins;
public TextMeshProUGUI CoinsText;

// Gebruik CinemachineVirtualCamera
public CinemachineCamera VCam;  // Cinemachine Virtual Camera referentie

public GameObject[] playerPrefabs;
int characterindex;

private void Awake()
{
    characterindex = PlayerPrefs.GetInt("SelectedCharacter", 0);
    GameObject Player = Instantiate(playerPrefabs[characterindex]);

    // Wijzig de Follow property van Cinemachine Virtual Camera naar de speler
    VCam.Follow = Player.transform;  // Dit is nu correct voor Cinemachine Virtual Camera
    
    numberofCoins = PlayerPrefs.GetInt("NumberOfCoins");
    isGameOver = false;

    // Zorg ervoor dat er slechts één instance van PlayerManager is
    if (instance == null)
    {
        instance = this;
    }
}

void Update()
{
    CoinsText.text = numberofCoins.ToString();
    if (isGameOver && gameOverScreen != null)
    {
        gameOverScreen.SetActive(true);
    }
}

public void GameOver()
{
    isGameOver = true;
    gameOverScreen.SetActive(true);
}

public void ReplayLevel()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}

}

sterile reef
#

!pastebin

frail knot
#

alrightt

sterile reef
#

!pb

#

Fuc

somber nacelle
#

the command is !code

tawny elkBOT
somber nacelle
frail knot
sterile reef
#

Paste bin glitches out on lmao, I'll just view the wall

#

Oh

frail knot
#

it doesnt move the camera 😦 so i want to remove the camera to get the full level at one screen

crisp minnow
#

If you're trying to pan on introduction to a new level, you could setup multiple VCams and have a script that when the scene starts it activates the dolly camera and once that's done it shifts to the player cam

#

If you're trying to have it follow multiple players on the other hand you should create a players game object and put all players within that, and have the camera look at and follow that combined object

frail knot
#

No, the meaning of the thing was to let it follows the player but now it doesnt anymore it did at first but now not anymore so i want to delete that camera to get the full level in my screen, and no i have 1 standard character

crisp minnow
#

Oh so you can just leave the same camera with a single "static" VCam if you'd like. Don't have it follow anything just keep it still

sterile reef
#

I don't know what the follow does in a virtual camera, but can't you move the camera's transform?

crisp minnow
#

You can just delete all Cinemachine references in your script, you don't need to control anything for that, just setup the cinemachine cam correctly in the editor

sterile reef
#

Lupo clearly knows

#

Ignore me

frail knot
#

ooh alright i will try

crisp minnow
frail knot
#

thanks mate @crisp minnow it works 😉

crisp minnow
#

I work backend, my knowledge of visuals is next to zero 👌 Well, I'm glad we got lucky this time 😉

somber nacelle
frail knot
#

A new question i have a sign in my game but if i get onto that sign their is nothing happening (the meaning is once get at the sign that there mus loading a new scene thats the scene and this the script: https://paste.mod.gg/bmehtekwypfo/1

wintry crescent
#

Is there an oposite to [RequireComponent]?

#

Like a [PreventComponent]

#

to add on top of a monobehaviour script

frail knot
#

What you mean? Can u give an example

#

using UnityEngine;
using UnityEngine.SceneManagement; these 2 things isare standing

wintry crescent
#

the 2 components should never exist together on a gameobject

vestal arch
frail knot
wintry crescent
#

I just want one script to hate another script and refuse to be on the same gameobject together

#

if adding script B removes script A, that's also fine

#

but I'd rather have an error instead

dusky lake
#

I mean you could work with onvalidate and check for other components

wintry crescent
#

I guess I could achieve it through executealways awake... but that feels icky

vestal arch
wintry crescent
vestal arch
#

but yeah no "disallow other component"

vestal arch
dusky lake
#

then that will be your friend

Only runs once when you add or manually press reset on a component

vestal arch
#

what you described is what you want, not an issue

#

does it not happen?

#

do you get any errors or logs?

#

you've given very little info to work with

frail knot
#

Wait lemme explain better

#

So the meaning of the sign, is if player comes on to that then it have to load "Level 2" (a brand new scene) but now it doesnt do anything, the script is on it, the box collider is on it but still nothin

vestal arch
#

are you getting any of the logs in the script you showed?

dusky lake
# wintry crescent onvalidate runs SO often though
public class Example : MonoBehaviour
{
        void Reset()
        {
#if UNITY_EDITOR
            if (gameObject.GetComponent<OTHER_COMPONENT>() == null) return;
            EditorUtility.DisplayDialog("Component incomatible", "This component is incompatible with OTHER_COMPONENT", "OK");
            Destroy(this);
#endif
        }
}
solemn ember
#

hello my people

#

currently I have this for the hitbox, which is working nicely

#

however I realized, it only detects one collision when I activate it 😦

#

see here, I'm hitting both, but only one is detected

dusky lake
#

any errors in the console?

solemn ember
#

nope, no errors

#

I was asking chatgpt, and that thing said I should use overlap box

somber nacelle
solemn ember
#

yeah... oof

somber nacelle
solemn ember
#

XDDDDDDDDDDDDDDDDDDDDDD

dusky lake
#

it helped me fix build errors that i couldnt find at all online more than once, on other topics it fails horribly

solemn ember
#

chatgpt is goated

#

that's my bestie

dusky lake
#

dont rely on it too much

frail knot
solemn ember
rugged pond
#

Why my raycast depends more on world position and less on mouse? From certain spots i can rotate it on 360 degrees while on others to only like 80-90 degrees. I've tried to log mouse position and it looks correct

Here i didnt move my mouse and only moved character but ray still moved

private void Update()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); // Vector2 variable

//if (InputUtilities.PressRBM())
if (InputUtilities.HeldButton("UseAlt")) // holding rbm
{
    Debug.DrawRay(transform.position, mousePos, Color.red);
    Debug.Log($"Mouse position: {mousePos}");

    RaycastHit2D hit = Physics2D.Raycast(transform.position, mousePos, interactRange, layerMask);

    if (hit.collider != null)
    {
        IInteractable interactable = hit.collider.GetComponent<IInteractable>();
        interactable.Interact();
    }
}
}
leaden ice
#
Debug.DrawRay(transform.position, mousePos, Color.red);```
#

DrawRay expects one position and one direction

#

you are giving it two positions

#

Same with your Raycast

#

if you want to use two positions, instead of DrawRay and Raycast, you should be using DrawLine and Linecast

rugged pond
#

Oh, i thought it would use mouse position as a direction, thank u

frail knot
#

this is all on the sign

worthy prawn
#

Hey, does somebody know a way to change shadow color? I want completly yellow shadow, but I didn't find anything about it

rigid island
worthy prawn
frail knot
rigid island
frail knot
#

yea thats my bad

rigid island
#

do you have at least 1 rigidbody on the player?

frail knot
#

nope it does nothing at all the whole code not even errors or sum, so yea think just gonna do it with buttons and yep i do

rigid island
#

Oh I see why..

#

You're in a 2D game

#

using OnTriggerEnter

frail knot
#

yep i'am

#

okayy

rigid island
#

Unity has 2 physics systems, one for 2D and one for 3D
OnTriggerEnter is for 3D, use this version instead

frail knot
#

okay

#

good to know

#

so not using ontrigger enter?

rigid island
frail knot
#

oki

#

@rigid island ❤️ ❤️ Thanksyouu

rigid island
frail knot
#

that was the thing i was looking for 🙂 i appreciate it

rugged pond
#

Is it safe to moving a part of code from Update() to a method and then call this method in Update()? It became pretty big at this point and i afraid it may break something if i break it to multiple methods outside of it in the first place

rigid island
#

you're calling the same code, no reason it wouldn't be safe

rain minnow
rugged pond
#

Yeah, i know it worth to split big code fragments to simple parts but i was afraid it may lose some data bc of update behavior (i mean constant updating a much of data)

#

Thank u

rigid island
rain minnow
rugged pond
#

Got it, thank u

young yacht
#

hey does anyone know how to fix "failed clustering job" when baking lights in unity? im using HDRP

worthy prawn
#

Hey, does anyone know a way to change shadow color which gameobject casts? I want completly yellow shadow, but I didn't find anything about it. I am using URP

dense pasture
#

so i've got a boot scene (additive scene stack) but its annoying having to switch scenes or go through the whole initialization process to test various parts of a single scene because i dont have my singletons in those scenes. is there a natively supported way to sort of have all of my singleton entities carry over scenes in the editor (not runtime) or do i gotta do some hackery?

clever lagoon
dense pasture
heady iris
#

you can use that to execute code when you enter play mode (or when the game starts, in a build)

#

I use this to instantiate my singleton prefabs

clever lagoon
#

not sure what you mean about dups- dont put it in there if you have one, but otherwise, yes. @dense pasture

heady iris
#

(which I load from a Resources folder)

dense pasture
dense pasture
heady iris
#

No. You use that to make Unity call a static method.

clever lagoon
dense pasture
#

yea im looking over it, haven't finished reading

dense pasture
heady iris
#

(and stick them in DontDestroyOnLoad)

dense pasture
#

right

#

aite that sounds about right

#

so prefab something like this (the "Core" parent) with a dont destroyonload in it's monobehaviour, and then instantiate that from the RuntimeInitializeOnLoadMethod call

clever lagoon
#

^ I like that

heady iris
#

Yep

#

I use that to bootstrap my entire game

dense pasture
#

rawk

heady iris
#

the Game Controller is pulled out of Resources, and then it instantiates other prefabs

dense pasture
#

i think to avoid the scenedirector from trying to load the scene stack at runtime, check if it's on the boot scene or not

heady iris
#

normally, it's guaranteed to be loaded while in the splash-screen scene

#

(not the unity splash screen, but another one i made, haha)

dense pasture
# heady iris I have editor-only code that checks if we're in a non-menu scene

lol, btw do you do anything like split your lists of scriptable objects up into separate children on something like a GameData object? for the sake of keeping clutter down? is that worth it? i'm looking at what i have now but its a very small collection, i can imagine when each table has like 200 entries it will be a nightmare

heady iris
#

I do have several "catalogue" objects

#

for example, I have a singleton SO that holds every settings category

dense pasture
heady iris
#

in turns, those holds settings (and other settings categories)

dense pasture
#

i'm thinking of splitting these all up into child objects

#

but the parent would roll them up at runtime

heady iris
#

Is the order of those objects important?

steady bobcat
#

if you use resources/addressables you can load many similar objects in bulk

heady iris
#

or do you just need access to them?

dense pasture
#

theres an enum that references them by index

heady iris
#

ah, okay, so order matters

dense pasture
#

sort of

heady iris
#

I was going to suggest an editor script that just finds them all and assigns them for you

dense pasture
#

i wrote a tool that generates the enum class files automatically and reorders them

#

long as no one changes the SO names it wont cause any headacheds

#

and even then is just a find/replace

#

i could also make the SOs accept a string that determines their name in the enum list

#

so even if the SO name changes it keeps the ref, but that could look confusing from a readability standpoint. either way its mostly idiot proof

#

(and i'm the idiot)

#

its also only really for the sake of accessing these from code. most of the things they're being used in only need to be in this table if i need a code reference

steady bobcat
#

eh id have the enum in the object and at runtime build say a dictionary for safer quick indexing.

steady bobcat
#

well yea that part is easy, its having them in the correct order that i dont like

dense pasture
#

even if the order changes, the code doesn't need to, the enum will rearrange itself automatically

heady iris
#

and you're serializing enum names, not the values, correct?

dense pasture
#

yup

steady bobcat
#

then why

dense pasture
#

wait what

#

no no im not serializing anything. for the identity SOs its just a straight int enum starting from 0 correlating to the index in the game data list

heady iris
#

and you don't serialize the enums anywhere?

steady bobcat
#

Yea id just have the Enum serialized in each object and not care about their index

heady iris
#

they're strictly used in code?

#

the enum values will change as the enum is reordered (if you don't assign explicit values to each name)

dense pasture
#

this is all it does

#

if i change the order in the game data and regenerate it'll just move them around

#

any use in the code wont change

#

the int value will thats all

#

there might be something i'm overlooking that'l bite me down the road but i'll refactor if i see it coming sooner than later

#

this IS the refactor of realizing using string names for things in my frameworks wont scale well so i switched to using SOs as ID markers

#

this was originally using string literals to reach out to things. now it's just the same SOs being used in that collection on game data, but with ways to pull them in code

#

most of these tools will just be using the SOs but i have support for custom c# script to direct cinematics too so sometimes i need to access them from code easily

heady iris
#

yeah, that's an issue i've run into as well

#

sometimes it's inconvenient to reference an asset

clever lagoon
dense pasture
#

its easy until you change the name of "Player" to "Character" and now have to go hunt down all the cases of using that string in 500 cinematic scriptable objects

#

constants can get you around that problem in code, but for editor tools... yeuch

dense pasture
golden chasm
#

is there anyway to delete player default data using UGS CLI?

#

I can list players and delete their accounts but it does nothing with the cloud save default data

rigid island
wheat cargo
#

What is the difference between Transform.TransformDirection() and Transform.TransformVector()?

rigid island
# wheat cargo What is the difference between `Transform.TransformDirection()` and `Transform.T...

This operation is not affected by position of the transform, but it is affected by scale. The returned vector may have a different length than vector.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.TransformVector.html

This operation is not affected by scale or position of the transform. The returned vector has the same length as direction.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.TransformDirection.html
gotta love the manual eh?

young yacht
young yacht
#

how did you do it?

#

right now im using a script i got from github to make buttons in the inspector

dense pasture
#

that will run whatever is in the if block if the button is clicked

young yacht
wheat cargo
rigid island
#

idk about uniform but more of them being anything above the normal 1,1,1 gets scaled by anything above it or under

#

since anything * 1 stays the same, if you got anything above or lowerr then yes ur vector now gets affected by that scale

wheat cargo
#

Yeah, the scale is already at (1,1,1), so my issue might be coming from something else.

heady iris
#

it just means all three axes are equal

#

but yes, at a scale of [1,1,1], it's the same outcome

wheat cargo
#

Yeah I realize that now, but I meant 1,1,1

heady iris
#

similarly, if you're at the origin, TransformPoint will behave just like TransformVector

#

and if you also have no rotation, then...well, nothing happens

#

you are now the identity matrix

wheat cargo
#

So, have this code which draws the direction of the velocity vector, and it works and appears smooth when I run.

I have a "simple" replay system that I wrote which records data at 10 fps, then on playback it interpolates the data between recorded frames. This appears to be working. The objects position and rotation are just as smooth on playback as when it was recorded.

I'm not recording the velocity vector data, just recalculating it the same way on playback based on the objects position. But the velocity vectors are choppy in playback.

private void Update()
{
    if (_targetTransform != null)
    {
        Vector3 velocityVec = (_targetTransform.position - _lastPosition) / Time.deltaTime;
        velocityVec.Normalize();

        _lineHandle.SetValues(_targetTransform.position, _targetTransform.position + velocityVec * _length);

        _lastPosition = _targetTransform.position;
    }
}

void IHandleReplayStartAfterFirstFrame.HandleReplayStartAfterFirstFrame()
{
    _lastPosition = _targetTransform.position;
}
wheat cargo
#

Okay so I was incorrectly calculating recording frame delta time like an idiot, but the problem is still persisting.

Changed this:

_frameDeltaTime = _recordingFps / 60f;

To this:

_frameDeltaTime = 1f / _recordingFps;
#

Soooo the choppiness of the lines have a direct correlation to the recording fps. If I increase the recording fps, the lines are less choppy.

I'm really unsure why that is happening, because the lines script knows nothing about the replay system. It is just looking at the transform which is being interpolated.

wheat cargo
#

If I draw _targetTransform.up vector from the target transform's position it is not choppy, even at a 5 fps recording. It has something to do with the velocity calculation, which again I don't understand since it is calculating it with the interpolated position on the transform.

cosmic rain
wheat cargo
cosmic rain
#

Relying on custom execution order is not ideal. Should structure your code such that you don't need to rely on it.
But anyways, the execution order is not the cause probably.

#

Thinking about, it does make sense that velocity changes would be discreet

mellow eagle
#

!code

tawny elkBOT
wheat cargo
wheat cargo
mellow eagle
#

no

#

sorry I was trying to post some code to my friend on WhatsApp

cosmic rain
# wheat cargo What do you mean?

Well, think of the position points that you have(the interpolated one). Try to visualize them on paper. Draw a line between them. You'll see that the longer the line is, the more visible difference is between the lines(velocities)

mellow eagle
#

was lazy to find the correct channel

wheat cargo
#

otherwise the replay would look choppy too

cosmic rain
wheat cargo
cosmic rain
# wheat cargo otherwise the replay would look choppy too

It is not because the difference between the positions is small enough for the brain to not perceive that it's discreet. But the velocity vector the longer it is, the more distance there is between the tips of the vector when you turn. This difference makes it easy for the brain to perceive the discreet change.

cosmic rain
wheat cargo
#

I'm not drawing the magnitude of the velocity vector, I'm always drawing it with a fixed length with the direction of the velocity

cosmic rain
#

It's not ideally smooth. It looks a bit better probably because the differences are more precise.

cosmic rain
wheat cargo
wheat cargo
cosmic rain
cosmic rain
wheat cargo
#

I'll record the velocity into the replay as well then

cosmic rain
#

Or even acceleration

#

But ultimately, you're gonna lose data/precision if you skip frames

wheat cargo
#

Okay thanks!

cosmic rain
#

Yeah, actually, with velocity or acceleration, the replay is likely gonna go out of sync(unless you record them every frame)

wheat cargo
#

Yeah that makes sense

#

Yeah so recording the velocity and using that in playback makes it smooth, so I guess the lesson today is don't do calculations on recorded interpolated data lol.

#

Thanks again @cosmic rain

fading hare
#

hi, I'm asking for help since this problem has been plaguing me for a day

#

im having an issue with navmesh agents where their walkpoint is inaccessible, the agent won't move, yet isPathStale, CalculatePath and pathStatus all return that the path is valid

#

when the agent is selected, the gizmos showing the destination and path flicker

rigid island
latent latch
#

by any chance are you recalculating every frame

rigid island
#

also you always get best results when you use SamplePositon

fading hare
#

currently im picking a point, offsetting it by a random amount, and making sure there is ground beneath it with a raycast

#

sometimes it does pick a wall which is fine, but even with a partial or seemingly complete path the agent won't move sometimes

fading hare
rigid island
#

if you call set destination every frame that can be issue, I think they changed something that now makes agent stop when it recalculates every frame

fading hare
#

ahhh

#

let me see

#

it seems much better now! no flickering, and the agent always moves until the walkpoint becomes truly unreachable

#

one more question I do have though

#

in this case, the destination is unreachable, but a partial path is formed

#

is there a way I can check if the agent has reached the end of the partial path?

#

nvm! found a way

#

thank you both of you, it was really helpful

rigid island
fading hare
#

apparently .destination returns the closest available position, not the one you've set originally

rigid island
#

interesting

fading hare
#

dont want people getting the wrong impression

rigid island
#

ah I see whats different SetDestination vs .destination

#

I think

fading hare
#

you can use it to set the destination, but unlike SetDestination, you can use it as a variable

#

where as SetDestination is a method

rigid island
#

they both return value, but destination returns you the position

#

SetDestination returns a bool

fading hare
#

yep! seems like it

rigid island
#

don't sleep on SamplePosition 🙂 its a good method to use to give better accuracy to calc

fading hare
#

oh right let me look into it

rigid island
#

for example Clalculate path wouldnt work properly for me unless the two points were run through sample position

fading hare
#

im struggling to understand its purpose?

rigid island
#

I wouldn't worry about it now, you might need it later for more advanced purposes.

#

it just returns the point onto the actual mesh from your position . You might need to make enemy go to a point on navmesh and if its not close enough to the navmesh this helps it "snap" on to the navmesh . Useful also if you don't have something solid underneath or anything to raycast on but still need a point on the navmesh

fading hare
#

ohhh!

#

I'll definitely keep that in mind!

#

im now having success purely going based of off the closest point to my intended destination, but this is probably because i just want the enemy to walk randomly rn

#

im sure there's a very good use for what you're suggesting

rigid island
#

yee i have a crab/spider type enemy that jumps from sidewalls navmesh to ceiling navmesh then to floor navmesh, sample position is a must for me 😅

fading hare
#

neat!!

earnest gate
#

Hey guys, I got to make a game!

worthy prawn
#

Hey, does anyone know a way to change shadow color which gameobject casts? I want completly yellow shadow, but I didn't find anything about it. I am using URP

latent latch
#

That's actually a little tricky as far as I know. You either have to modify the shadow data directly if you truely want to modify the shadowing, or go about it an alternative way like post-processing, or using masks

fleet gorge
#

duplicate the default lit shader and change shadow colour from there?

#

this shader needs to be applied to every mesh that casts and receives shadows

fiery steeple
#

Hey,
Is there a way in Rider to get extra info / documentation on the popup that shows up when I hover over methods, properties, etc... that Unity made (or even my own documentation for my own methods, variables, properties) please ? Because the little popup right now is borring and doesn't give much info

Please ping me if any answer 🙂

worthy prawn
worthy prawn
cosmic rain
vague slate
#

Gizmos.color Do properties like that reset between each instance of DrawGizmos method?

cosmic rain
young yacht
#

whats the best json package for unity?

#

trying to serialize lists with jsonUtility but its a shit fest

somber nacelle
#

if jsonutility isn't cutting it for you, then use json.net. however jsonutility shouldn't have any issues with serializing a list provided the list isn't the root object, it must be part of another object

young yacht
#

i'd have to create a wrapper around it

#

but its quite the shit fest to read no?

somber nacelle
#

then just do that, it takes 2 seconds 🤷‍♂️

#

you could even give the wrapper object an indexer so you can directly treat it like a list, or implicit (or even explicit) conversion operators to make getting to/from a root list object even easier

flat marsh
#

Hi! I'm facing an issue with my attack speed in my game. Basically, I want to have different weapons, with different movement speeds, however, although my code is correct (I have confirmed this several time by checking values, as well as the actually rigid body value) it does not translate to increased movement speed in game. I'm not sure what's causing this as all the values are correctly set. Here is the code for my character controller, and my attack Script where I'm setting these values. https://paste.ofcode.org/smdr44nEFRFmNFfiQeSiXz. Thanks in advance!

P.s. I use a rigid body to move my character, with rigidbody.velocity
Pps. Please ping me if you have a slotuion otherwise I wont see it XD

azure frost
wintry crescent
#

That is so weird. I have a script that is in a folder named Editor, but it gets included in a build

#

why could this be? Is it the fault that It's a separate assembly?

#

building right now results in a compilation error, but wrapping the script inside the Editor folder in #if unity_editor solves the issue

#

I'm just confused why the Editor folder is included in a build

#

Unity 6000.0.37

#

so newest one

plucky inlet
#

What is the script doing? is it really an editor script?

wintry crescent
#

it's an editor script yes

#

and wrapping the whole file in #if unity_editor makes it compile

plucky inlet
#

And it derives from : Editor?

wintry crescent
#

yea

#

yyy no

#

: PropertyDrawer

plucky inlet
#

😄

wintry crescent
#

but close enough

#

why?

#

the script works, it's not the issue

#

and removing it from compilation via #if unity_editor works

#

but why does the presence in a folder named Editor doesn't exclude it automatically

plucky inlet
#

you dont have to repeat that all the time 😄

wintry crescent
#

that's my question

#

i guess

#

I'm just perplexed

plucky inlet
#

I am wondering, if your editor folder is somehow misspelled or something

wintry crescent
#

copy pasted folder name: "Editor"

#

do you see a typo?

plucky inlet
#

Can you show your script, your propertydrawer?

thick terrace
#

is it in an asmdef?

wintry crescent
thick terrace
#

you'll need an asmdef for the editor folder too then

wintry crescent
#

🙃 I suppose so

thick terrace
#

you're telling unity explicity which assembly to put it in, and unity is doing what it's told 😛

wintry crescent
#

yea that's fair

steady bobcat
#

yea an Editor folder inside an asmdef doesn't do this magic anymore

slender bear
#

And, you can name the folder whatever you want at that point.

karmic stone
#

hello, i modified a scriptableobject script, and it doesnt think its a list of a new item, but the old item.

leaden ice
#

You probably have a compile error. Check your unity console.

karmic stone
#

ScriptableObject in inspector still uses List<Item>, which is just a guid and itemdetails scriptableobject

trim schooner
#

Got any console errors? (show us a screenshot)

karmic stone
#

i know how to debug, just forgot to check console, and forgot to use refractoring when changing the scriptableobject.

#

totally my fault

trim schooner
#

Oh, I didn't see Prae had already said to check the console

edgy ether
#

Ok so i dont know if this is possible but i'll try to explain what i wanna do.
i think it's a bit time wasting for me to always create a script just to move a single float on a single object. there be various reasons to do it, but i never could specifically use the same script on all the different scenarios.

So i was wondering, is it possible to create a script that lets you plug any float to the variable to be modified without having to create a specific one?

i mean like, within the inspector, take the x on a transform and drag it onto the designated property elsewhere on the inspector and just let that new property handle the value of the float?

#

like, the idea was to be non-specific on the float but being able to drag the float to it will just make it manipulate it

steady bobcat
leaden ice
#

You could make a function that takes an Action<float>

#

and modifies it in some way

#

you could use DOTween

#

there are many options, but currently the question is a bit too vague to be answered concretely

edgy ether
#

im finding it difficult to explain. but, you know how you can create a property field that can drag a component or game object or transform into the field in the inspector? well i was hoping to be able to do the same with a float or vector 2/3

leaden ice
#

they are value types

#

But what you can do is use interfaces and delegates

steady bobcat
#

well regardless you need a way to serialize the property or field name

#

e.g. name. But no idea if you could even make this doable via drag/drop without some custom popup to let you pick a field/property

vestal arch
leaden ice
#

of course they are structs

steady bobcat
#

they are a value type

leaden ice
steady bobcat
#

managed code moment

edgy ether
#

im not too familiar with the term delegate or interface (im a bit illeterate on the terminology of c#), but the main idea i had was probably to get the component in question and find a way to list all of the public variables using the the type of value, like vector 3 or floats.
then i can just pick the one i want to modify from the array

leaden ice
vestal arch
leaden ice
#

it's not generally a good practice

#

turns out all primitive types are structs

#

so value type == struct

vestal arch
#

i hate it so much

leaden ice
#

reference type == everything else

steady bobcat
leaden ice
#

then you reference that thing

#

that's the idea behind the Atoms architecture

vestal arch
#

i mean c structs are just a list of other types so.. i guess primitives would be 1-member structs but i don't like the thought of that LMAO

leaden ice
hexed pecan
edgy ether
#

that's pretty interesting. i'll see if i can find anything on it being used. dunno if i wanna put this in blind lol

vestal arch
steady bobcat
#

Can that allocate the float on the heap?

leaden ice
#

structs have constructors too

steady bobcat
leaden ice
#

it just creates a float with the value of 0

edgy ether
vestal arch
steady bobcat
vestal arch
#

(does that work in c#)

edgy ether
#

probably if you take that last semicolon

vestal arch
#

ah as an expression yeah

#

nah doesn't seem to work

edgy ether
#

also @leaden ice i don't mean to ping you but i just realized that you have been like the main person answering my questions over the past few years. so here's my heartfelt thanks ❤️

vestal arch
#

ah c# has new { x = 0f }

#

but it's readonly

cold parrot
# edgy ether that's pretty interesting. i'll see if i can find anything on it being used. dun...

you should be aware, if you use the SO architecture (atoms) for runtime mutable values, you can very easily murder your project and make it unmanageable (the paradigm is very powerful), but if you just wrap your primitives into SOs to enable your drag/drop in the editor for runtime-immutable values, you've essentially created a form of type-object with added configuration and that is a very powerful and generally required architecture (if you want to stay productive).

edgy ether
#

im reading up on serializable objects and serializable reference as we speak. it feels like it's sorta where i was looking

cold parrot
#

well, if you change public values on SOs, best of luck to your mental health

edgy ether
#

lol that's already in question with a lot of things i've been attempting

cold parrot
#

SerializeReference is also one of those things that explodes like a hand grenade in your pocket if you aren't careful. If you try to be clever, unity has many hidden traps waiting for you. Its great fun finding them all.

edgy ether
#

lol im already second guessing everything

#

this is from a video im looking at

cold parrot
#

there is a reason why traditionally you give everything in a game an ID and communicate between objects only through a mediator via that ID, not via direct object reference.

#

unity does that internally, but in c# land we're happy to make direct references, until it comes time to save & restore game state, add multiplayer or migrate between versions of that game state.

edgy ether
#

ah... well i'm probably going to back off from this one, but i do want to read up on this a bit more

analog rock
#

Anyone here have a paid subscription to an AI model for game dev? If so, which have you chosen and why? I'm trying to pick the "best" one to spend my money on and am having a hard time deciding

vestal arch
analog rock
vestal arch
#

i am, because most people asking stuff like that have that (lack of) background

lean sail
wheat spruce
#

ChatGPT is probably the best one, though when it comes to any LLM, its less about how good they are, and more down to knowing how to use it to get the most out of it. I dont think any of them are better at game-dev than another, just some are better at generating code than others

lean sail
heady iris
#

i would rather not hook up the infinite spam generator to anything on my computer

analog rock
#

but anyway thanks folks

#

Im off of here

vestal arch
#

mmm im not seeing any aggression there, they just stated a fact of asking for help

wheat spruce
#

I'll use gpt sparingly just to touch stuff up or if im too lazy to clean up a function, small tasks like that I find gives pretty reliable results

wraith cobalt
#

In any case, not a coding question.

storm sleet
#

i usually hear that is not good to use async in unity, but is it ok in this case:
I have a component to manage other components forming a sate machine
when a component completes a task i want to inform the manager, that manager will then check the state (involves a loop through certain components and check their state), so i thought it could be good idea to make this "message" async without await to avoid blocking the thread
note: its not implemented its just a thought yet here is pseudo code

if(something){
  _ = assetManager.TaskCompleted();
  // some other small tasks
}
public async Task TaskCompleted()
{
  AssessState();
}
void AssessState()
{
//depending on state loop opver relevant components and if appropriate go to next state and trgger actions on next state (basically just setting flags on those components)
}
steady bobcat
leaden ice
steady bobcat
#

also dont do _ = Func() you will find out the hard way why you never see exceptions in the console

heady iris
#

it reminds me of how I felt about things like unity objects becoming null when i was just learning the engine

#

i can't tell what is and isn't allowed

steady bobcat
#

Async is useful and exists because it makes writing code easier vs the alternative where you have callback hell.

leaden ice
#

yeah I don't use it much myself but many others do

#

I stick to coroutines which I have a better understanding of

steady bobcat
#

if you understand coroutines then you can use async

storm sleet
leaden ice
#

I mean I understand async, but I don't understand the little nuances and such as well as I do for coroutines. For example the exception handling pitfalls

steady bobcat
steady bobcat
storm sleet
#

I dont think i was understood. I have this method i wanna call but i want to forget i dont care about what happens there, but regarding the exceptions maybe i should just set a flag and forget the async

#

I was just hoping to make the state assessment in the same frame

steady bobcat
#

use UniTask for tasks instead to solve the issue

#
public async UniTask DoThing()
{
    await UniTask.Delay(TimeSpan.FromSeconds(1000));
}

public void Start()
{
    DoThing().Forget();
}
storm sleet
#

Oh its new to me, ok so i can use unitTask as regular tasks , and use this forget() will continue execution of start() regardless of the duration of the task

steady bobcat
#
public async UniTask DoBadThing()
{
    //This is bad and will freeze the main thread
    while(true) {}
}

public void Start()
{
    DoBadThing().Forget();
}
#

as a reminder, tasks still run on the same thread (usually) and cant just go on forever. The example above still freezes the main thread

storm sleet
#

Isnt that the same behaviour as a regular "void"? I mean i dont know when the unitask would run. I have to read the documentation on that but i cant rn, just to make it clear, i am calling DoThing() on update, its not infinite loop, lets assume its .05ms(fictional) but i dont want to hold the update method as there are many other objects with an instance of the state machine and it adds up, the result of the "assessState" will just set flags after it does its work and it will not affect anything on the same frame and the next state is not active and only thing it can happen is next state is activated on next frame

latent latch
#

It is funny how little I do any multithreading. If I need some complex operation done quickly I'd just let the gpu handle it

steady bobcat
#

coroutines let you run code over many frames cus when you yield it "pauses execution" for the function and unity comes back later to continue it.
Async can do the same when you await something such as await UniTask.Yield() to let us wait till the next frame.

latent latch
#

oh these run on the main thread right

#

I think I've used these before

steady bobcat
#

The UniTask delay/yield functions use the player loop so they work basically the same as coroutine delay/waits do

latent latch
#

I think I was having problems with web exports at one point with them, but maybe that was another issue

storm sleet
#

Hmm . I didnt understand is if its worth doing this, as i dont want to await, i mean i want it ready before next update on same object, maybe i should await it on late update or something but that only applies if its not blocking the update

steady bobcat
#

you are making less sense. can you show some code to demo what you want to do??

storm sleet
#

I showed

#

Less sense? I said from start i dont want to await (on update) i got confused because you say unitask blocks the tread, i didnt understand if it blocks the update

latent latch
#

you can always check conditionally then break out the execution loop if that's what you're asking

#

like if you wanted an infinite cycle until you decide you want to yield from it completely

steady bobcat
#

okay let me give a better example

storm sleet
#

I am not asking about breaking any loop

steady bobcat
#
public void Start()
{
    DoThingOverManyFrames().Forget();
}

private async UniTaskVoid DoThingOverManyFrames()
{
    while(this != null)
    {
        if(transform.position.y > 0)
        {
            Debug.Log("Thing!");
        }

        //Wait for next frame
        await UniTask.Yield();
    }
}
storm sleet
#

I said " send a message " that will trigger a method and that method takes some computation, not much but there are lots of objects doing this, but its a message, no await, no return, just dont want to block execution of updates

latent latch
#

by loop I mean that it doesn't block the thread, but it'll always execute this logical sequentially every update until you decide you don't want to anymore

storm sleet
#

Lol but i need this loop every "message" its not over many frames, i never said or meant that is supposed to last many frames

#

The message will not be sent every update, on every object,, its conditional

steady bobcat
#

you are being to vague still i dont really get what you want to do

storm sleet
#

How vague? Call a method and continue execution without waiting for it to complete or any return

#

I dont think this needs any context really

steady bobcat
#

call and dont await it???

#

its like doing StartCoroutine()

latent latch
#

not sure what you're looking for otherwise but it sounds like you do want to do a lot of work as quick as possible without blocking the main thread, so that's probably it.

steady bobcat
#

you can do Task.Run() to execute code on a worker thread (not main thread) but you cannot interact with most unity apis it will just throw an exception

#

Awaitable is unitys own Task replacement just like UniTask

storm sleet
#

I can use c# i just dont know when i shouldnt in regards to async. I read briefly some documentation but i will continue this tomorrow thanks for your help

naive swallow
#

Does anyone know of a way to get BuildPipeline.BuildAssetBundles to not create an extra empty bundle file of whatever the destination directory is? If I have three bundles and I build to a directory named win, I end up with four bundles and four manifests, one of them being an empty bundle named win. It's kind of annoying to always have to clean up afterwards.

karmic stone
#

Hello, I'm looking to use unity Custom assembly system, bc i have like 30s compile time with a simple project. The problem being, i cannot use the assemblies because the built in assemblys are not in my project, and when i add a assembly definition to my folder containing all my character stuff, it tells me that it cannot find InputActions. how do i force unity to put all their scripts into my project so i can include it in custom assemblies

hexed fjord
#

does an error happen if you try to StopCoroutine("name") a coroutine that has already stopped by reaching its end?
im trying to set up a failsafe that stops it before trying to start a new one

steady bobcat
#

the default Assembly-Csharp auto references all of them for you hence you not needing to do this before

hexed fjord
leaden ice
#

but really don't use the string version

#

the string version is bad

latent latch
#

https://i.imgur.com/rJ1lvOh.png

[Button(enabledMode: EButtonEnableMode.Editor)]
private void OnValidate()
{
    foreach(Renderer render in materialRenderers)
    {
        render.sharedMaterial.SetVector("RelativeCoordinates", transform.position);
        EditorUtility.SetDirty(render.sharedMaterial);
    }

    SceneView.RepaintAll(); 
}

Can't seem to update this material in code for some reason. Even at runtime, which could itself be another issue, I'm not seeing any changes from this material instance itself.

steady bobcat
#

its _RelativeCoordinates

leaden ice
latent latch
#

OH

#

ty

leaden ice
#

which is really annoying and silly

steady bobcat
#

like _MainTex

leaden ice
#

IDK why they give it two names

latent latch
#

been a minute since I've accessed this stuff directly

#

Would be nice if shader graph had those property binders that the VFX graph has to just reference stuff directly on the editor

weak thicket
#

How do I smooth an unsteady incoming integer data stream so the output is gentler?

cold parrot
#

if you have some statistical knowlegde about what clean data would look like you could use a kalman filter, interpolation, smoothed reconciliation or some simple exponential smoothing, but it depends a lot on what value ranges you are dealing with and whether the time-interval is unstable (unreliable connection) or the values themselves (noise).

weak thicket
cold parrot
#
weak thicket
#

👍

#

Thanks

karmic stone
#

Hello, i moved my scripts into 7 different domains that at most reference 2 other assemblys. However, that doesnt improve compile time, i still take 20s to compile to run, how can you improve compile time using code?

somber nacelle
#

you're certain that it is the compile time that is taking that long and not the domain reload or something?

karmic stone
#

i know that my scene reload takes 2s, and this domain reload happens everytime i edit any script i have. the point of assemblys is to reduce this WILD compile time

somber nacelle
#

domain reload != compiling

karmic stone
#

what can cause this massive of a domain reload besides my scripts, i have a simple scene with 5 trees, 1 100 by 100 untextured terrain, and a player character

karmic stone
#

that would be it, wouldnt it.

somber nacelle
cold parrot
#

if you restart the editor and its faster, you probably have a leak of some kind

#

you could also disable domain reload

karmic stone
cold parrot
#

but after compilation, you still need to reload

#

from what you describe you should be entering playmode in < 10 seconds

arctic sparrow
#

Has anyone here thought about something like this before? I feel that it would be very handy to have an animation track in Timeline that can persist if the timeline is paused.

https://youtu.be/Ixx2obcn_kM

Notice how the characters still do a "wait" animation while the cutscene timeline is paused instead of just stopping their animation?

I have a bit of a plan on how to do it, but I'd like to know if someone else has thought of this before me.

Seeing this scene takes me back to the first time I played Twilight Princess, shortly after its release and on my brother's new Wii. This has been my favorite game ever since.

Please enjoy my selection of cutscenes from Twilight Princess HD. You can find the playlist here: https://www.youtube.com/playlist?list=PLluwu6OC0qmfDTQQnqmIUN_jVqNiTtN0...

▶ Play video
cold parrot
steady bobcat
#

Ohh i did this once! made an animation continue even when the timeline was paused

karmic stone
arctic sparrow
cold parrot
steady bobcat
cold parrot
#

it just means that unity evaluates way more items than needed/expected

karmic stone
steady bobcat
#

I feel like unity could have made this a feature where the animation could keep playing and loop even when the timeline is paused but hey ho

cold parrot
#

common leaks are from new Texture2D, new Mesh, new Material and assigning/reading .mesh and .material without destroying the instances/automatic-duplicates. Or from holding references to any of these in managed shells.

karmic stone
#

i do not have anything editting mesh, the only thing i do have is to draw the boxcollider of a plot using Vertz tools, so that may be the leak

cold parrot
somber nacelle
karmic stone
cold parrot
karmic stone
#

oh thats super super helpful

cold parrot
somber nacelle
steady bobcat
#

and by restart i mean kill process and re open

cold parrot
karmic stone
cold parrot
#

its also incompatible with debugger use... but at least it makes adding a debug.log very quick

karmic stone
#

yeah, i can deal with the 1s to recompile/domain reload after restarting my editor, but i will keep it on hotbar if i ever need it

#

since theres drawbacks to hotreload

cold parrot
#

building your game so it supports disabled domain reload is helpful

#

but you gotta learn to live with 10-30 sec for enter play mode after re-compile on projects of a decent size

karmic stone
#

yeah, my game problably doesnt even need domain reload rn. i disabled it on play mode enter. the problem was domain reload on script compliation

cold parrot
#

just be glad its not a C++ game

#

then you'd be waiting 20 minutes

#

i read somewhere that they made the killzone games without any kind of real level editor and iterations (change of value to ingame test) of 2+ hours

karmic stone
#

that just sounds like true pain. and btw yeah i checked and my game is all set to not need domain reload rn. i always found static variables not very useful with how mono scripts have to handle finding other mono scripts

steady bobcat
#

sbox's hot reload is amazing so hopefully we can get something this good when unity ditches mono

void timber
#

Does anyone know why when the player.transform is moved to a position after touching the spikes the linecast suddenly doesn't detect anything with the Player tag anymore (even if I make a new game object and assign the player tag to that and set it to what the linecast is targeting)

naive swallow
void timber
leaden ice
#

ok i was probably wrong

#

anyway time to start using Debug.Log

naive swallow
void timber
naive swallow
#

Check with the console open and see if it's detecting that object, or if it stops detecting anything alltogether

naive swallow
#

Check to make sure your respawn point is at the same Z position as the player and enemy

karmic stone
#

does anyone know how to make variables in class reference a outside datasource? Like the bindings for ui. I pass a ref to a data object, set variables equal to the data object, but they dont ref the source, even a Quaternion and transform. i can pass by ref keyword but i was told its unessisary because objects are already pass by ref.

cosmic rain
#

You could use a property that access the target field/property in real time though

karmic stone
#

why cant you make 2 references reference the same place in memory?

leaden ice
leaden ice
#

can you write your home address down on two pieces of paper?

cosmic rain
#

But not value types

leaden ice
#

If you actually have references you can.

leaden ice
# karmic stone

instead of duplicating all this data just keep a reference to the PlayerData object.

karmic stone
#

ah ok, so i need to have an object wrapper.

leaden ice
#

this whole Bind method should just be:

myPlayerDataRef = data;```
#

assuming PlayerData is a class

karmic stone
#

will do.

cosmic rain
steady bobcat
#

this isnt rust

naive swallow
#

Left to our own devices, mankind will re-invent the pointer hell they have only just escaped from

steady bobcat
#

I love rust and the borrow checker and i like Cpp too

karmic stone
steady bobcat
#

c# has this too what are you smoking

karmic stone
#

i cant do the thing with references im able to do in java

dusk apex
karmic stone
#

yes, im saying in java i can just choose for a float to be pass by ref if i want it

cosmic rain
steady bobcat
#

void MyFunc(ref float f)

dusk apex
#
b.value = 3;
var a = b;
a.value = 5
Debug.Log(b.value);//5```
karmic stone
#

ah, ok, then i am mistaken.

wispy frigate
#

Just booted up a new project, got hit with this without doing anything

leaden ice
wispy frigate
#

How do i delete it?

dusk apex
#

From the package manager

modern creek
wispy frigate
wispy frigate
modern creek
#

... i can see the icon for it right on your pc :p

steady bobcat
#

also can be used on the web

wispy frigate
#

But that acc is also is the owner of my server so I can’t just log out and lose it

steady bobcat
#

close unity project, delete Library/PackageCache folder, re open project, ???, profit

pastel halo
#

is unity 6 worth upgrading to? I know that unity tends to change API and i'm trying to make that decision since i'm reading its more stable.
I wanted to start looking into DOTS since some of my projects involve mass unit spawning, and trying to make a gameobject with a tiny class still lags when it hits like 50-100k units, even with the most rudimentary logic.

There's also the issue of having to debug any plugins or api additions/removals which could be large swaths of code or very little. I'm mainly interested in better performance and more fleshed out systems like DOTS/ECS if that works (last i read animator is still not supported by DOTS and it requires a custom class?) and the whole issue of dots and gameobject interactions.

Getting alot of mixed information online. Anyone that has a large project and has upgraded, any major issues or notable bugs compared to 2022.3 (unity 5)? Also curious if the debugging is any different or more accurate, since that's generally a tricky thing to track down sometimes even with stack tracing. The plan would be to clone my current project then import/fix any issues.

somber nacelle
# pastel halo is unity 6 worth upgrading to? I know that unity tends to change API and i'm try...

one thing to note is that unity 2022.3 is not unity 5, unity 5 is a version that came out a decade ago.
but if you are in the middle of a project it is usually not advised to upgrade to a new major version unless there is some specific feature you need so that you don't have to go through all the trouble of ensuring all of the assets you use are compatible or updated for the new version.
as for your DOTS related questions: #1062393052863414313

weak thicket
vestal arch
vestal arch
cosmic rain
vestal arch
#

value types don't have it, ie fundamentals in c/c++ or structs in c# or primitives in java/js, but there are ways to get a pointer/reference/object for each of these cases

vestal arch
night patio
#

does sprite atlas batch sprite animation?

cosmic rain
supple quiver
#

Hi guys, I'm having a translation problem with Asian languages (Korean, Japanese, and Chinese – both TW and CN). Russian and Latin are working fine, but I'm facing issues with these. Does anyone know anything about this?

#

I also tested other fonts, like NotoSans Korean.

#

same issue

#

never mind, it has altas res, I forgot to test it.

storm sleet
# pastel halo is unity 6 worth upgrading to? I know that unity tends to change API and i'm try...

if you make a copy and have good internet or time to spare i suggest you try. 100k objects is exactly the strong suit of DOTs, you will have to learn ECS and probably change your way of programming, but i dont know the actual state of DOTs for your purpose (animation) at the moment as i only used it in preview and not with animations but it was awesomely powerful for huge amounts of "entities", i believe its only better since it has been released..
Note: I dont know if you watched this, but seems that animation its possible in DOTs didnt bcs i am not using it but i follow him so i knew this was out there ||https://www.youtube.com/watch?v=KvabbZKrUHk || and this is just a plug to a course on the same topic ||https://www.youtube.com/watch?v=P01egjRl2cs ||

worthy prawn
#

Hey, does anyone know a way to change shadow color which gameobject casts? I want completly yellow shadow, but I didn't find anything about it. I am using URP

cold parrot
worthy prawn
#

Not only some

vague slate
#

I have a rotated rect (it's technically a camera view). And I need to project positions outside of it on it's edges.

Rotated rect is represented by 4 Vector2 (each vertex of rect).

Any idea how can I do that?

safe zinc
#

How do I prevent Unity from using 100% of my CPU when building shaders(Windows, Unity 6)? nothing seems to work.

steady bobcat
vague slate
#

oh, I think I know

steady bobcat
vague slate
#

well, what I had in mind is different: I know that each point is associated with 0.1f or 0.9f of viewports

#

so I thought I could just convert using those maybe

heady iris
#

This may be an "uphill both ways in the snow" take

night storm
untold apex
#

has anyone had issues reading pen tablet delta values with the new inputsystem? finding it spikes from regular values like 1-5 to 80 or 100 for very minor movements(that should be 1-5), doing similar mouse movements doesnt have the same issue

heady iris
#

are you getting inconsistent results, or are they just very large?

untold apex
#

inconsistent results

karmic stone
heady iris
#

A delta value should not be multiplied by the frametime

#

since it's already an absolute amount of change, rather than a rate of change

cold parrot
woeful hamlet
#

How do I optimally add Unity Events to a prefab (specifically one that I place via the editor instead of spawning it via a non-prefab spawner)?

#

 private void Start()
 {
     collected.AddListener(ScoreScript.Score);
 }

 public void OnTriggerEnter2D(Collider2D collision)
 {
     ScoreScript.Score();
     Destroy(this.gameObject);
 }```
#

ScoreScript is a singleton class and Score so far does nothing but increment an int score and print a debug message. Adding the event didn't seem to work, but directly invoking the static message does.

thick terrace
#

your code there doesn't show where the event is invoked at all, so it's hard to see the whole picture

woeful hamlet
thick terrace
#

ah 😄

rigid island
#

wouldn't ScoreScript be the one with events?

woeful hamlet
#

How so? The cup is the item that gets collected.

rigid island
#

scorescrpt is the one tracking the score no?

rigid island
woeful hamlet
#

So the prefab is only pinging the ScoreScript to make it do its thing and send out the Event?

#

The UnityEvent<int> means that the Event can pass on int parameter when it gets called, right?

rigid island
rigid island
#

a listener can listen even if it doesn't need the value exactly but is interested in the event, Eg a Sound player

#

if it has that static instance to be accessed with you can do
ScoreScript.Instance.AddListener so this event

//Another script like UI or Sound Listener
    void OnEnable(){
        ScoreScript.Instance.OnScored.AddListener(ScoredEvent);
    }
    private void ScoredEvent(int score){
        Debug.Log($"scored! do something from here");
    }```
#

or use the inspector too. you just cant make event itself static for that, use static instance of class that contains the event, w singleton pattern as shown ^

woeful hamlet
#

So the collectible notifies the ScoreScript by invoking its static method, then the ScoreScript broadcasts an Event, and everything else that cares aobut the Event subscribes to it with AddListener or dragging it in the editor, correct?

#

Sorry if it sounds like I'm just repeating you, but I learned that I need to be able to paraphrase/repeat stuff in my own words for my understanding.

woeful hamlet
rigid island
#

sometimes I use Awake though . Depends on the situation but mostly using onEnable/onDisable

#

I generally don't use Start unless whatever I'm subscribing to needs to set itself up in Awake

#

event then I rather just make the ref get bootstrapped in or have the singletons have a slight sooner exec order