#archived-code-general

1 messages · Page 432 of 1

rigid island
#

are you still parenting it to the car?

gloomy helm
#

no

#

also mb for late response people cameover

lyric veldt
#

does anyone know why

red ocean
#

what

lyric veldt
#

the editor and the actual game looks really differnet

red ocean
#

the camera

#

idk

lyric veldt
#

wut

red ocean
#

i need help with something

lyric veldt
#

chat what the sigma

cosmic rain
lyric veldt
#

i cant find it

crisp rover
#

Is any one know what import do I need for ECS customized shader to support Dots rendering? I can not find any information on the official documentation?

crisp rover
#

Oh, the reason why it looks different is that Light only show up in run time

#

which means that it will have light effect in game mode

#

but when you editing it, the light is not rendering for you.

lyric veldt
#

ohk ok

#

thanks

#

ok

#

cookie???

craggy veldt
#

when you're using a regular Tasks, they don't know exactly whether the continuation should happen this frame, next frame or start of frame .. basically it's out of sync with the main loop

#
  1. you either want to roll your own dispacher using the scarcely documented PlayerLoop api, or 2. you dispatch them with a coroutine later down the line with NextFrame, EndFrame etc, or 3. Make a poormans dispatcher by having a while(myActionQueue.Count > 0) in Update method
#

or the ultimate way, use Awaitable<T>

wheat spruce
#

Like this one for a flashlight

scenic dome
#

Anybody know why it says "Failed to find entry points" in the Unity complier?

upper pilot
#

How do I change animation speed preview?
Changing animator layer speed to 0.1 works fine at runtime, but when testing the animation in "animation" it plays really fast.
How do I make it match the runtime speed?

viscid plaza
#

Every time I generate a mesh, it's shape is completely wrong
This is supposed to be 512x512. I've tried my own code, ChatGPT, internet scripts, anything. All of them look like this.
And before you ask, the scale of the object they're attached to is 1 1 1. Changing it to 1 1 5 "fixes" it

hexed pecan
#

Which is 65535

#

512 * 512 is 262144

#

(You should be getting a warning about this in the console)

teal wadi
#

can someone help me with my code??

pine olive
teal wadi
#

i dont know what this means

#

ive been trying to fix it but its not working

#

this is the code

swift falcon
#

Is there a way to enable / disable fullscreen render pass features at runtime via a script without changing the actual asset?
I can do this

public FullScreenPassRendererFeature fullScreenPassRendererFeature;
fullScreenPassRendererFeature.SetActive(true);

but when the game ends, it changes the asset in the editor too

viscid plaza
hexed pecan
viscid plaza
#

Ah, then I assume that will not be a problem.

hexed pecan
#

200x200 would fit into 16 bit format though

viscid plaza
#

Yeah, must be creating some extra vertices accidentally somewhere.

teal wadi
#

can someone help me idt it has anything to do with my code tho

vestal arch
#

!ask

tawny elkBOT
teal wadi
#

mb

#

My player keeps falling through my plane and idk how to fix it

vestal arch
teal wadi
#

alr alr

weak gale
#

how do i fix this issue? on start when i load up my game the main menu scene and the title scene load up at the same time, i have a script for the scene transitions here:

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

public class SceneTransitionScript : MonoBehaviour
{
public List<string> sceneOrder;
private int currentSceneIndex = 0;

void Start()
{
    if (sceneOrder.Count > 0)
    {
        currentSceneIndex = sceneOrder.IndexOf(SceneManager.GetActiveScene().name);
        if (currentSceneIndex == -1)
        {
            currentSceneIndex = 0;
            LoadSceneByIndex(currentSceneIndex);
        }
    }
}

public void LoadNextScene()
{
    if (sceneOrder.Count == 0) return;

    currentSceneIndex = (currentSceneIndex + 1) % sceneOrder.Count;
    LoadSceneByIndex(currentSceneIndex);
}

public void LoadPreviousScene()
{
    if (sceneOrder.Count == 0) return;

    currentSceneIndex = (currentSceneIndex - 1 + sceneOrder.Count) % sceneOrder.Count;
    LoadSceneByIndex(currentSceneIndex);
}

public void LoadSceneByName(string sceneName)
{
    if (sceneOrder.Contains(sceneName))
    {
        SceneManager.LoadScene(sceneName);
    }
}

private void LoadSceneByIndex(int index)
{
    if (index >= 0 && index < sceneOrder.Count)
    {
        SceneManager.LoadScene(sceneOrder[index]);
    }
}

}

tawny elkBOT
weak gale
rigid island
weak gale
tawny elkBOT
weak gale
tawny elkBOT
weak gale
#

ok there

rigid island
#

ok stop using the command plz

weak gale
#

sorry

rigid island
#

you are meant to read it

weak gale
#

oh alr

rigid island
#

you still sent it wrong.

#

Paste the code on the site, save and send back generated link

weak gale
#

alr

rigid island
weak gale
#

got it

#

ima see if there is any videos on fix, if not i will send it there

rigid island
#

a video on a specific thing you're having issue with rather than someone looking over it ?

weak gale
#

well both methods did work for some other stuff before

rigid island
#

do ya thing

viscid plaza
tawny elkBOT
viscid plaza
#

Apologies.

#

Also there's weird gaps in all of the "cubes" except the one at 0 0 but that's a problem for another day.

hexed pecan
#

So is this a completely different/new script? I'm confused

viscid plaza
#

The first script was just a test script. What happened was I got issues with the original script, so I made a test script to see if the issue was with my code or just Unity.

hexed pecan
#

I see you generating 512*512 but still not using 32bit index format

viscid plaza
#

Oh sorry, I override the size in the editor.

#

Or am I

#

Oh, that would explain it, would it.

hexed pecan
#

I dont see anything that does

#

Lol

viscid plaza
#

I hardcoded 512 into part of the code, other parts change dynamically.

#

My bad.

#

Thx for picking that up!

#

Well now with it set to 128 and nothing else changed, they're invisible (instead of that horrible purple color). I can select them, and their bounds are visible, but they don't render

hexed pecan
#

Looks like your code is adding triangles in counter-clockwise order:cs triangles[triIndex++] = topLeft; triangles[triIndex++] = bottomLeft; triangles[triIndex++] = topRight;

#

Unity uses clockwise winding order

viscid plaza
#

You are correct, thank you sir!

atomic hatch
#

i'm trying to make my game look fancy. i'm new to this. i'm adding some vfx, some camera shake, lighting, and shadows. it's a top down. what other topics should i be looking into?

#

some "juice" i think i'm meant to call it

rigid island
atomic hatch
#

... i guess to me, a question about buying shadow asset libraries is more a code question than an issue of game design? but okay, i'll try over there

rigid island
#

"should I buy this asset" isn't directly a coding question

quaint crypt
#

In unity 2022 I have attack animations and combos set up.
I need to implement a damaging system. (Melee combat, damageable entities, hp, etc)

I was thinking of creating 2 main components: Damageable and Damaging.

The Damageable component always adds a trigger collider to the object it is attached to.
It also adds HP (hitpoints) to the attached GameObject.

The damaging component listens to OnSwingStart and OnSwingEnd animation events to enable the collider on a weapon. (When the swing starts, the collider is enabled).
When there is a collision between the Damaging collider and the Damageable collider, damage is inflicted.

I really like this system because it's simple to implement, and can lead to interesting emergent properties between systems.
How can i improve this system? What are its drawbacks? Are there better alternatives?

swift falcon
#

Hi, does anyone by any chance know of a public UnityEvent drawer that enables collapsing of some type? Scripts in inspector can become too long

leaden ice
latent latch
#

callbacks a pain for animations

latent latch
#

rather, query is a pain*
I prefer trigger colliders and shaping them to animation frames

#

one problem though is the trigger information is usually not available till next fixed frame

leaden ice
#

but trigger colliders have the problem of not giving you contiguous detection

#

they're limited to discrete collision detection and yes you have the whole timing nightmare, no?

latent latch
#

true, I wish rigidbody had like collider.cast like box2d has

leaden ice
#

yeah you need to wait for physics sim before you get a hit

quaint crypt
quaint crypt
swift falcon
leaden ice
quaint crypt
#

@latent latch Sorry, just saw your explanation

leaden ice
#

unless we're talking about hundreds of these things

quaint crypt
#

nope, just a player and max 10-15 damageable entities let's say

leaden ice
#

yeah I would worry more about functionality and clean architecture.

leaden ice
#

like setting BoxCollider.width/height for example?

quaint crypt
latent latch
#

Specifically how fighters do it. The'll usually have a 1 frame window for the hitbox

leaden ice
quaint crypt
quaint crypt
latent latch
#

full rigidbody detection would be nice for sword slashes, but that could run into detection problems if it's too quick. Depends how rigidbody is feeling, but usually I'm writing that interpolation.

leaden ice
#

that's my main reason for preferring the immediate query, but I'm sure colliders have other advantages.

quaint crypt
#

I'm just looking for some simple Valheim style combaty

#

nothing too realistic

steady bobcat
swift falcon
steady bobcat
#

well there are other better means like interfaces and in reality its still dependant on that script existing there with a named function

#

if you rename the func, it just silently breaks! If its via code, compile error!

fiery iris
#

does anyone know how to access a global texture in a rendergraph renderer feature?

vague cosmos
#

I cannot figure out why the top code logs to the combos list I have, but the lower code doesn’t? The upper code is the DPAD, and the lower are face buttons. The code executes in both, but just doesn’t save to the combos list?

hard estuary
# vague cosmos I cannot figure out why the top code logs to the combos list I have, but the low...

Make sure that logs are not commented during testing. It's worth checking out if the script was saved. You're using else if phrasing, which means the later ifs won't be checked if the earlier ones meet condition. Make sure that all actions are enabled (I think they're disabled by default). Sometimes Unity glitches and code changes don't affect the game - in such cases restarting Unity helps (I haven't got such error in newer Unity versions though).

steady bobcat
#

it may be a pain when debugging input related things but you can add trigger conditions to breakpoints to aid in this

vague cosmos
#

Ok, thanks!

exotic crypt
#

sorry, posted some rubbihs without reading what was actually happening, ignore if you read it 🙂

indigo verge
#

When using Unity's inbuilt Pooling system, is there a way to specify what is retrieved from the pool, or should I implement multiple pools when pooling objects of multiple (similar) types?

Example, I am currently setting up a setup to spawn Visual Effects based particle systems, for things like blood splatter and dust clouds, using different assets for different types. Should I be using a system that pools all of these "Particle Objects" in one Unity ObjectPool, or a system that makes one pool for each type of Effect-producing object?

rigid island
#

I do have a Generic pooling class I use that has everything i need though

#
public class ObjectPooling<T> : MonoBehaviour where T : MonoBehaviour
{
    public static ObjectPooling<T> Instance { get; private set; }

    private IObjectPool<T> objectPool;
    public IObjectPool<T> ObjectPool => objectPool;

    [SerializeField] private bool collectionCheck = true;
    [SerializeField] private T prefab;

    [SerializeField] private int defaultCapacity = 20;
    [SerializeField] private int maxSize = 100;

    [SerializeField] private int amount;
    [SerializeField] private int createdAmount;

etc

inner yarrow
unkempt cobalt
inner yarrow
unkempt cobalt
inner yarrow
inner yarrow
#

Huh, I don't think it worked.

#

It's confusing me so much, because it just looks like random noise, and to my knowledge, I don't have any sort of post-processing or global illumination turned on.

cosmic rain
#

Also, this has nothing to do with code. Next time post in #archived-code-general or some other relevant channel.

inner yarrow
# cosmic rain 1. Try creating lighting settings(press "new" button). You don't have any assign...

Yeah, that didn't change anything. Thanks for the suggestion though. Also I know it's not really code related. I wasn't sure if it was somehow connected to the mesh generation stuff since the non-generated meshes are working fine, so I figured I'd do it in here in case someone had had a similar problem with mesh generation (also because other channels don't seem to get answered), but I'll relocate in future.

cosmic rain
#

Or is it just the video quality?

inner yarrow
#

Oh I'm stupid. I was missing this little line of code.

cosmic rain
#

Then I didn't get what the problem was I guess.

inner yarrow
#

idk why that fixed it, but it did, so I'm not going to question it too much. It does happen slightly when zooming into the bottom of the capsule, but you shouldn't be doing that in game anyways, so I think this'll work. Thanks for the help!

lean sail
#

!collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

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

inner yarrow
# cosmic rain Then I didn't get what the problem was I guess.

I don't know if you care, but it was happening again with some other faces, and I finally remember what's causing it, so I figured I'd share for anyone curious. I forgot that normals are connected to the individual vertices instead of the faces, so if you have 2 faces sharing at a sharp corner, you ideally want to duplicate the vertex for each face, so that it can have all of its vertices' normals pointing in the same direction as the face to prevent weird lighting shenanigans.

edgy ether
#

ok so i know this isnt necessarily unity's fault (or i dont believe it to be)
but is there a way to prevent visual studio from randomly automatically adding lines of code to my scripts?

#

was wondering why my game wasn't building

#

and it said a script i made was trying to use some things that i never asked it to use at all

#

me, obviously never put it in the first place realized visual studio's intellisence may have done this

#

i like the suggestions, but i dont want them to automatically do stuff behind my back

night harness
#

as in the usings?

edgy ether
night harness
#

its what happens when you accept (intentionally or unintentionally) an ide auto complete recomendation that would require said using

edgy ether
#

ah, i need to find out how to turn that off

old elk
#

of the what

daring cloud
#

anyone have any tips for cleaning up Physics2d.Collider2d.DestroyShapes? I am loading a scene and destroying existing colliders is taking minutes to execute (there are ~20,000 of them)

#

they arent simulating, half are used for static collision half are click colliders

vestal arch
#

it just got cut off, the period might be from ellipses

stable osprey
# vague cosmos I cannot figure out why the top code logs to the combos list I have, but the low...

try cleaner code:

Dictionary<MyAction, string> actionToComboMap = new();

void Awake() {
    actionToComboMap.Add(LeftAction, "Left");
    actionToComboMap.Add(RightAction, "Right");
    // ...
}

void Update() {
    foreach (var (action, comboName) in actionToComboMap) {
        if (!action.WasPressedThisFrame()) { continue; }

        Debug.Log($"{comboName} was pressed");
        combos.Add(comboName);
        time = 0.35f;

        break;
    }
}

... and even cleaner would be if each action contained the combo name and maybe even activation logic:

List<MyAction> actions;

void Awake() {
    actions = new List<MyAction>() { LeftAction, RightAction, ... };
}

void Update() {
    foreach (var action in actions) {
        if (action.WasPressedThisFrame()) {
            action.OnPressed(combos, out time);
            break;
        }
    }
}
#

but your issue likely comes from the fact that each action breaks. So if LeftAction activates, the other actions won't even be checked.

craggy veldt
stable osprey
#

well might as if (action.TryPress(out time)) { break; }

hexed pecan
rancid gulch
#

I am looking at making a little battle game in unity, where you control circles that serve as divisions/batallions. My only problem is drawing frontlines. How would I go about drawing a dynamic frontline in unity 2d where the line would adjust to units moving around, split up into encirclements and all that? I thought about using line renderers, but I have no idea how I would go about doing this. Any suggestions?

leaden ice
rancid gulch
#

Frontline would be a line that shows the border of the two players in a battle, the frontline would need to more around and adjust with the units and battle, as well as possibly splitting up at times in case encirclements form.

leaden ice
torn aspen
#

Guys what do you think the maximum AI’s ability is for coding in Unity right now? Like, what functionalities would it be able to code (eg. a multiplayer 2d game, an endless 3d runner etc)?

clear basin
#

Guys, what's better to do with killed enemies that don't respawn? Destroy() or disable them?

leaden ice
#

Why would you keep it around if you don't need it anymore?

clear basin
hard estuary
hard estuary
# clear basin Guys, what's better to do with killed enemies that don't respawn? Destroy() or d...

In most cases (probably 95% of games) it's better to get rid of them. In some cases you might want to use pooling - hide them and use in a different place if needed (just because they don't respawn, it doesn't necessarily mean such enemy won't be spawned in another place). Some games might occasionally want to keep dead units on the scene for some extra interactions (e.g. looting or necromancy) or keep only a small piece of information (e.g. location of their death and who they belonged to).

steady bobcat
#

It's easy to use the unity ObjectPool<> to set this up

old elk
old elk
#

ellipses use 3 periods

#

i just thought it was funny lmao

vestal arch
old elk
#

Yeah that's what I thought initially but

vestal arch
#

damn

old elk
#

I'm guessing the documentation in code is auto generated and what happened is it tried to find a link to a class called "mesh filter", but couldn't, since that hyperlink just leads to a manual page

#

so it just ended up omitting "mesh filter" entirely lmao

knotty patrol
#

Hey I'm trying to create items with ECS and until now I've used Scriptable objects is there a way I could use it with ECS?

somber nacelle
knotty patrol
#

lol ok thx

worldly stirrup
#

So, I kinda made my 2D character controller that can stick to surfaces a bit too good, as it can stick to any surface, but i want it to detach and move off of the ground

#
    {
        overlapped = Physics2D.OverlapCircle(groundCheckPos.position, groundCheckRadius, level);
        RaycastHit2D hit1 = castRay(rb.position, -transform.up, slopeCheckLength1, Color.red);
        rayed = hit1;
        grounded = rayed && overlapped;
        if (grounded)
        {
            getGroundValues(hit1);
        }
        else resetGround();
        doSlopeCalc = Mathf.Abs(slopeDownAngle1) >= minSlopeAngle;
        transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, -slopeDownAngle1), timeOfRotation);
    }```
urban summit
#

what's the best ide for unity?
also whether it does consume lots of ram or not

worldly stirrup
# worldly stirrup ```private void checkGround() { overlapped = Physics2D.OverlapCircle...
    {
        if (ceilinged)
        {
            velocity.y = 0f;
        }
        if (!grounded)
        {
            velocity.y = Mathf.Max(maxFallingSpeed, velocity.y + delta * physicsMultiplier * playerGravityForce);
            isJumping = velocity.y > 0f;
            isFalling = !isJumping;
            return;
        }
        isFalling = isJumping = false;
        velocity.y = slopeDownAngle1 != 0 ? groundSpeed * -slopeNormalPerp.y : 0;
        rb.position = slopeHitPoint + (Vector2)transform.up * posOffset;
    }```
somber nacelle
urban summit
snow siren
#

I have a problem: I have an animation for an attack with a sword, but the animation only plays for one frame instead of the full animation. Is it because I'm doing this in Update()? (I'm using Unity C#)

leaden ice
snow siren
#

thats my code

#

i guess so

#

first time working with animations

leaden ice
#

No, pay attention to your if statements, you're not doing it every frame.

Start debugging your code with Debug.Log and the Animator window

latent latch
#

I guess a better question would be what's the best way to get contact points from a skinmesh render bone against a unity collider

sullen urchin
leaden ice
#

It won't really tell you the penetration at all

leaden ice
sullen urchin
wise kindle
#

What does [ExcludeFromDocs] do exactly?

cosmic rain
wise kindle
#

Right, I'm trying to take a peek at the Quaternion.LookRotation method to see how the math behind it works, but I can't find where it is

cosmic rain
#

It's probably implemented on the C++ side, so we don't have the source code

#

But it should be pretty plain and similar to what other engines do

somber nacelle
desert mist
#

What approach is advisable for setting an Observer Pattern scripts observed class dynamically? For example, I have a Health class, and a HealthBarUI class. The Health class calls an Action when the health value is changed, and the HealthBarUI class observes this action and adjusts the UI element accordingly. This is working correctly.

However, this requires a reference to the specific Health instance on the player, as this Health class is intended to be re-used on any object that has health, including enemies and breakable environment objects. Would this be set as part of a game management class also in charge of spawning the player object?

wise kindle
#

Not an expert, but I'd make it an interface

#

Probably a wrong way to do it, but it's how I'd do it

desert mist
#

I just assume that having a lot of calls in awake or start all take place for that kind of function on the player is generally not advisable because maybe there is a different, better way to do it

wise kindle
#

Wait, how many destructible objects to you plan on having in a single scene?

desert mist
#

Not a whole lot, but I would like to keep my performance budget low to include low end devices

#

More than 10 but less than 100 on screen at any given time

wise kindle
#

I mean, if all you're doing is changing a float variable, I don't think it's going to be that big of a deal

desert mist
#

Well the player HP bar is not the only reference I need to be setting or calling, it was only an example. If I had 100 health instances(including 1 player), I dont want to loop through them all to find the one on the player if I dont have to

#

I also thought that the player spawn could call an action, with a reference to the player object, but then the HealthBarUI would also need to subscribe to that action as well, and I am having trouble with determining how to approach setting which class is observed since the objects are not pre-spawned in at scene load so setting the reference in the editor directly wouldnt work

wise kindle
#

You could use a method to find a gameobject with a specific name, or tag, and then search for its health bar class component, then call the method for decreasing health.

desert mist
#

Yeah but if I have a lot of classes that need references to different classes on the player, using Find would cause a spike for all of that

#

This class is placed on a UI element, not the player

#

Again, this is only a single class, but if other UI elements and other scripts need to also observe the player Health instance, using Find every time seems like not the right call to me

wise kindle
#

Hmmmm... I'm not too sure, but if instead of finding by name, you find it by tag? If say there is only one tag called Player, it's faster and more optimized than finding by name

#

Does the player change?

#

Like, is it destroyed at some point in the game?

desert mist
#

It does not change but the instance would sometimes be destroyed and instantiated, yes

#

As the game has multiple playable characters, each is a separate prefab

#

This is where my idea of an Action in the spawn logic came from, but then every object in the scene that needs it would have to observe that class as well

wise kindle
#

Okay, the idea I have is, instead of destroying the characters, why don't you just pool them? You deactivate them and then the data is still in cache, that way you don't have to find the players all the time, only once when they appear

desert mist
#

Well this still doesnt really solve the problem because the observed class is still not set

#

I appreciate your help though

wise kindle
#

I'm not sure how to solve that issue though, other than telling you searching by tag is better for large amounts of objects

desert mist
#

I guess I should just do it the way that makes it work first and then worry about it later if it causes a problem

cosmic rain
pale wagon
#

hi everyone

#

im new

wheat spruce
#

Hi, new

#

😏

night patio
#

is there a search term to find all missing script in a scene?

twilit gull
#

`using StarterAssets;
using UnityEngine;
using UnityEngine.Playables;

public class CharacterSwapper : MonoBehaviour
{
public GameObject char1;
public GameObject char2;
private GameObject activeCharacter;
private bool playerState;

void Start()
{
    activeCharacter = char1;
    char1.SetActive(true);
    char2.SetActive(false);
}

void Update()
{
    playerState = activeCharacter.GetComponent<StarterAssetsInputs>().swapCharacter;
    if (playerState) // Check for input
    {
        activeCharacter.GetComponent<StarterAssetsInputs>().swapCharacter = false;
        SwapCharacter();
    }
}

void SwapCharacter()
{
    Vector3 position = activeCharacter.transform.position;
    Quaternion rotation = activeCharacter.transform.rotation;

    activeCharacter.SetActive(false);
    activeCharacter = (activeCharacter == char1) ? char2 : char1;
    activeCharacter.transform.SetPositionAndRotation(position, rotation);
    activeCharacter.SetActive(true);
}

}
`

I'm attempting to make this darn code swap between two charaters. This code is stored on an empty object, and char1 and char2 are the characters i wish to swap between. However, "playerState = activeCharacter.GetComponent<StarterAssetsInputs>().swapCharacter;" is not working. Does anyone know why it won't take the bool, and instead returns "NullReferenceException: Object reference not set to an instance of an object
CharacterSwapper.Update () (at Assets/Scripts/CharacterSwapper.cs:21)"

night harness
#

It’s failing to get that component

twilit gull
#

how can i fix that

night harness
#

That object needs to have that component

twilit gull
#

I need to give the empty object the StarterAssetsInputs script?

night harness
#

I mean yeah

#

It can’t get what doesn’t exist

twilit gull
#

activeCharacter.GetComponent<StarterAssetsInputs>().swapCharacter;

right here, i'm referencing the activeCharacter, and grabbing the bool from the other object. Why isn't this sufficient for the code?

night harness
#

either activeCharacter is null or activeCharacter doesn’t have a StarterAssetsInputs component

twilit gull
#

OH

#

i assigned char1 and char2 wrong

#

thank you 😭

night harness
#

While youre there

#

You should have references to these components saved

#

Rather than getting them every frame on update

twilit gull
#

how would I make that change

night harness
#

on phone so a little tricky but like how you have your gameobject fields at the top you can have a field for each StarterAssetsInput and either set them drag and drop style like your gameobjects or set them by doing that kind of getcomponent in start

twilit gull
#

okay thanks

hardy pasture
#

Shoud .meta files be source-controlled?

west lotus
#

Yes

lean sail
waxen matrix
#

i need waveform for some project
decided to use line renderer, and bake it into mesh
but im concerned about the verticles/triagles count
is there any other way to have runtime waveform?

steady bobcat
#

good god 7M, can you not sample at a lower rate for this mesh?

#

Could also make/update a texture instead with a compute shader

waxen matrix
#

can i get sample data with lower rate? i still need audio to be good

#

about texture, not sure how to do that..

steady bobcat
#

depends how you are getting this wave form. instead of using every single sample, you can use say every 4th. Having a vert for each one is clearly not going to fly.

waxen matrix
#

hmm, let me try

steady bobcat
#

I think a compute shader could work by giving it a block of samples and you can have each compute thread produce a column of pixels for the sample

waxen matrix
#

if i only knew anything about shaders

steady bobcat
#

try sampling at a much lower rate first and see how it looks. If it doesn't yield good results you can perhaps change it to get the average of a range of samples instead

waxen matrix
#

used 4, 8, 16
the 16 cuts it to 449k verticles
much better but still a lot
and i imagine what would happen with much longer audio

thick terrace
#

are you ever going to be able to see 449k verts at once? unless you're getting really close to this thing, maybe you can sample a number of times proportional to the size on screen?

waxen matrix
#

i guess id better off writing custom mesh gen for that 💀

waxen matrix
cursive moth
#

We came to the conclusion it's most likely due to the asset having it's own asmdef, any way to get around this?

late lion
late lion
# cursive moth Will try that, thanks.

Just remember that this is a hack, and Unity could change TrackAsset to not be partial anymore, in which case this won't work anymore. Assembly Definition References are not really intended for this, it just happens to work with Unity packages as well.

cursive moth
mortal thistle
#

Hello guys ! I'm trying to make something really simple :

  • Have a VideoPlayer that takes an URL to my remote server that hosts a video
  • Play the video

But I'm getting this error :
WindowsVideoMedia error 0x80004004 while reading <myURL>

Context: IMFSourceReader::WaitForSample in StepAllStreams
Error details: Op볡tion abandonn맍

The video file seems fine since it works if I put it directly in Unity.
The weird thing is that it sometimes work, sometimes doesn't...

Any ideas what could be the root cause ? Or how to solve this ?

cursive moth
distant trench
#

Hi guys, I am just wondering if I can get an input from somebody about my code. I have got an AI character which should be checking with a linecast to see if the player is in line of sight, and if the player does come within the line of sight of the AI it should start to move towards the player. however it doesnt seem to recognise that my player is there and doesn't want to find it

true heart
#

does your player have a collider?

distant trench
#

yes

vestal arch
distant trench
#

it isnt no.

vestal arch
#

have you debugged where the line actually is?

distant trench
#

I have a debug.drawline which isnt drawing the line

vestal arch
#

make sure you're looking in scene view

distant trench
#

it should draw from the ai character torso to the player torso but it doesnt

#

it doesnt show in scene view

vestal arch
#

show your code

#

!code

tawny elkBOT
distant trench
#

its the FindATargetVIALineOfSight part. the rest works fine if I drag the player into the lock on myself

vestal arch
#

don't put your debug line inside the if

#

and add extra logs to check if that point is being reached

distant trench
#

I added some debugs to see what isnt getting reached and it appears that from the CanIDamageThisTarget if statement and below isnt executing

#

but I think thats due to the fact that the ai isnt finding my character with the Physics.OverlapSphere

steady bobcat
#

i guess verify that the layers are correct. Id say use a debugger + move the retrieval of the layers to be seperate so you can inspect it easier

distant trench
#

I did that earlier and found that it is detecting all of the different parts for the character but it isnt actually detecting the player prefab

#

like it will find the torso and the head colliders and whatnot

#

but isnt finding the player one

#

and I have tried to do a GetComponentInParent which didn't affect anything

steady bobcat
#

If it overlaps many colliders... then it will return them all as results.

#

so either adjust layers to better filter out other colliders or verify why get component in parent did not work (perhaps the hit collider is not on the correct object at all)?

distant trench
#

I have just changed it so the debug prints out the parents name and it is detecting itself and the player but it isnt setting the player as the current target.

steady bobcat
#

use a debugger so you can inspect better

hexed pecan
#

Alternatively, have a component on the bodyparts that have a reference to the player

shadow wagon
#

I'm trying to figure out how I'd generate the map for my dungeon, on the left is what the in-game map would look like. On the right, I've simplified it down to a tree-like design. It feels like it shouldnt be that hard to generate something like that tree, but I dont really know where to start.

#

If I write it down as text, I get something like this

G1
G2
G3  ->  R1
G4      R2
        R3  ->  B1
        R4      B2
                B3```I dont know if thats actually helpful to figure out the generation, but its as far as I've got. Any thoughts?
shadow wagon
#

does that matter? surely if I'm creating a tree/graph, that wouldnt actually care about the location of each node

hexed pecan
#

Doesn't really matter tbh

#

What I like to do is run a "physics" simulation on the graph

#

Each node can have a radius and some connections

#

And then you iteratively try to relax the graph

#

By separating them circles

shadow wagon
#

yeah, I'd do a force directed graph once its built

hexed pecan
#

If the map doesn't have cycles then it's a lot easier

shadow wagon
#

I'd process it do actually produce the more aesthetically pleasing version of it, but thatd be a second stage

#

based off the rules I have with the dungeon itself, the more complex map on the left can be represented as the graph on the right

#

I lead with a simpler map as its easier to think about

shadow wagon
hexed pecan
#

Yeah I see. Not a problem

#

I prefer to do procedural generation stuff purely with POCOs anyway, no gameobjects involved until everything is ready and the objects need to be spawned

shadow wagon
#

to quickly illustrate the way it works if its not clear, you must always travel in the direction of a boss, so even though the graph shows 3 different red-boss locations, they're actually just the same room

dense rock
#

hey there, I want to make a text editor in unity similar to how notion works. Can I get some suggestions on how I could do that? I feel just a big inputField wouldn't quite do the job...
it's part of a bigger app that stores the written text in my database via my api, but I didn't think about needing a text editor

steady bobcat
dense rock
#

is that a package from the unity asset store?

steady bobcat
#

newer UI system thats similar to html and css in terms of elements and layout styling

dense rock
#

that's great. I'll look into it!

shadow wagon
#

honestly it would be so much easier if I my dungeon was going to be like that 😆

#

alas

#

so how could I generate the map like this?

#

Im not really sure what format to store it in

hexed pecan
#

Which stage is this exactly?

#

Just the layout?

#

I use a node graph (looks similiar to shader graph etc.) that defines the nodes that are allowed and what can be connected to what. I call it the layout source graph

#

I then toss it into a generator that makes sense of it and tries to place all the needed rooms while keeping them at certain separation distances and respecting other rules i have set up in some [SerializeReference] lists on the nodes

shadow wagon
#

this would be the first stage

hexed pecan
#

So it's sort of abstract

hexed pecan
#

(I don't really know what you are actually asking about)

shadow wagon
teal wadi
#

hey so im makinga multiplayer game but whenever i kill a player this error pops up

can someone help me?

shadow wagon
#

What sounds right is I draw a line, and that line MUST overlap at least 1 other line, then one side of the line after its intersection is found gets removed, then I draw the next line. Which would do this

hexed pecan
#

Generate a line
Pick a random point along that line
Generate another line on the random point
Repeat

#

Make a simple graph data structure to start with

#

With nodes and edges

steady bobcat
hexed pecan
#

And like a helper method that splits an edge into two

sacred estuary
soft shard
shadow wagon
tawny elkBOT
steady bobcat
hexed pecan
#

Not sure how you could produce something like this with a branching tree

sacred estuary
# teal wadi Destroy

You shouldn't call Destroy() for networked gameObjects, you have to call Runner.Despawn() on the server (if you're using Fusion, for Pun you should use PhotonNetwork.Destroy() instead)

teal wadi
soft shard
hexed pecan
teal wadi
#

like ive made singleplayer games before

#

this is the first time im using PUN

teal wadi
unkempt cobalt
#

it is a new way of structuring you have to adhere to at least for fusion 2 what im using it took a while to understand

soft shard
#

PUN also has sample projects and a discord as well, but I agree, multiplayer games is very difficult to make as a beginner, even difficult for experienced devs, so it could be a big undertaking to start with imo

teal wadi
#

i understand that but ive been trying to fix it for a while now and this is the only thing im stuck on everything else has been working perfectly

shadow wagon
#

it might be that one, but if you copy a branch over to another side of the tree and change a color, it works

soft shard
shadow wagon
#

there must only be 1 line per color, so the red meets yellow twice (at 1 and 2). the right hand side is what the basic graph would look like, and the middle is what I'd need to intepret it as

teal wadi
soft shard
# teal wadi yeah ive run into a couple problems but those were straightforward im just not a...

Fair enough, I would try to isolate the problem, make a new script and compare it to the docs, try PUNs sample projects that already handle destroy, see if you can get it working then compare the difference, or try adding some Debug.Logs and breakpoints and try to see whats happening frame-by-frame, and make sure the object your trying to destroy has a PhotonView properly setup on it - also make sure the object your trying to destroy has an owner (IE: was instantiated with PhotonNetwork as well)

teal wadi
#

oh alright ill try that

#

thanks so much

feral oak
#

I have hundreds if not thousands of pngs (animation frames) that I need to apply normal maps to in the unity sprite editor. Is there no way to apply them automatically, or mass assign?

I've attempted asking AI and they keep trying to make an Editor script for it, but they haven't been working. Is it possible to make it work?

steady bobcat
feral oak
steady bobcat
#

Ah right, are you trying to use the texture importer then?

feral oak
#

Like, so for example "tree1.png" will automatically get "tree1 normal.png" assigned as a normalmap to it.

steady bobcat
#

so make some static function and use [MenuItem] to call it in editor

#

if you want to automate it even better you can use UnityEditor.Selection to do this over many assets you select in the project window

shadow wagon
#

is there any way to do something like [DoNotSerialize], so if I was to write public int DefaultRoomWidth = 50; it will show 50 in the inspector and I can change the value in the inspector, but if I ever alter the value in the script, unity will update the inspector to match the change?

#

its annoying that once its set in the inspector, theres no way to get unity to read a new value that i explicitly set in my script

steady bobcat
#

well you cant have a serialized value AND it also use the default set in the class?

#

If you dont want to serialize it, use [NonSerialized]

vestal arch
shadow wagon
steady bobcat
#

indeed it does

shadow wagon
#

I still want it to show up there, but if I alter the code then that change should take priority

steady bobcat
#

then use something like naughty attributes (which can show extra "read only" values easily) or create a custom inspector editor

shadow wagon
#

ah, okay

#

I guess I misunderstand what the word "serialize" means

hexed pecan
#

It really means "save the data", but unity also shows serialized data by default

#

So they get used sort of interchangeably for saving and also showing in the inspector which is a bit misleading

shadow wagon
#

so why does unity not have something that detects whenpublic int DefaultRoomWidth = 50; changes to public int DefaultRoomWidth = 250; and overwrites the serialized value?

hexed pecan
#

Because you could lose work

thick terrace
#

it would be way more annoying if it wiped out all your changes in existing assets

feral oak
shadow wagon
vestal arch
#

ok, what if you change multiple properties

#

wait sorry brainfart

#

what if you have multiple independantly configured instances of a given script

#

for example in prefabs or prefab variants

vestal arch
#

and there's no observable difference between a value that's just the default and a value that's been tuned and happens to be the default

#

like maybe you set the default speed to 0 just as a placeholder, and in one instance you explicitly want it to not move, if you change the default with the behavior you're proposing, it'd make that single instance suddenly be able to move

#

what you're proposing isn't useless, it'd just cause more problems than it solves, unfortunately

#

that is, if it were unity implementing it editor-wide

lean sail
vestal arch
#

if you have a specific usecase where it does make sense and doesn't have these kinds of drawbacks, then it'd make sense to make an editor script or something

vestal arch
shadow wagon
#

I dont see it

lean sail
#

not on the component, on the inspector tab itself

shadow wagon
#

ooh, the inspector

vestal arch
rigid island
#

btw you can right click the script and HIt Properties and you can Debug view only that popped out window so it doesnt touch the original inspector UnityChanThumbsUp

vestal arch
#

or was that a different thing 🤔

shadow wagon
#

i wonder if I do something generally wrong with using unity, like I rely a lot on code and not too much on the inspector

hexed pecan
#

I mean it's an issue if you are so new that you don't realize that it's in debug mode

#

Which i have seen, yeah

#

But that's user error

vestal arch
#

if you edit everything in code you'll have to recompile just for tweaking values

rigid island
#

pop out the inspector for specific script you don't have to touch the original inspector

steady bobcat
#

some things dont need to be instance variables but some do. Id say it varies. If something can be static or const then i will use that.

#

needs to be shared by many instances? scriptable object!

lean sail
hexed pecan
#

Been recently trimming off a lot of static fields (like lists i reuse for procedural generation) after I started multithreading

#

And just pass around pre-allocated collections instead

#

Though I gotta see if I could still use static fields and lock 🤔

shadow wagon
#

something im trying to do more of is getting a scene in a state where most things are already configured and ready to go, too many times ive just constructed and configured loads of stuff in awake, like finding references to objects, when its far easier to just drag and drop to the fields instead

rigid island
hexed pecan
#

You can also add default references to a Monobehaviour if you select the script file

#

I recently heard that it works for non-monobehaviour stuff too, in unity 6 👀

steady bobcat
#

that only works for newly made components in edit mode and well cant be instances in a scene

hexed pecan
#

It's because these object references can't really have default value from code

shadow wagon
#

I mean, I do DI a lot but thats mostly just normal OOP design

thick terrace
#

doing DI the manual way is a pretty good idea anyway, the frameworks just automate some of the repetitive stuff

shadow wagon
#

ive struggled to find an example that actually explains it in a way that sounds useful

#

the theory of it, I understand

#

all the examples feel too daunting or "why would I need to use a DI library for that"

thick terrace
#

it's most helpful on larger projects with a lot of interconnected systems, especially if you want to write any unit tests

rigid island
steady bobcat
#

I make do manually providing required dependencies but sometimes its just easier having a system that "distributes" them for you

#

i expect most big projects dont only use monobehaviours so it fills that gap

rigid island
shadow wagon
#

i mixed up library and framework, i just meant something like zenject

#

most of this doesnt mean anything to me, (ive never heard of auto-mocking), which probably means its not of any use. But surely there must be something to it that could help me out

rigid island
#

personally done all other DI in .net but in unity I never really needed such a custom system

#

but also Im a solo dev and most of my projects have been small

#

its pretty easy to make a basic system by creating a simple Bootstrapper object

shadow wagon
#

atm I'm trying to ditch the way I was doing rooms in my dungeon, in hindsight it shouldnt have been done the way it is

languid hound
#

What way are you currently doing it

thick terrace
shadow wagon
# languid hound What way are you currently doing it

Load the dungeon scene, generate an array of RoomLayout (just a struct with dimensions and settings for a room). I pop the first item from the array, and the room gets built using it. Then once you move to the next room, I pop the next layout and reload the entire dungeon scene again, (only this time the map exists so it wont generate a new array)

#

it felt like a good idea at first

#

I think once I get the actual terrain generation for the room in a state thats not a bunch of placeholders, it should make it easier to correct my past mistakes

bleak garden
#

I have a question about model clipping, is this the right channel?

hexed pecan
#

Or polygon clipping/computational geometry?

wintry crescent
#

Is there a nice built-in type to select a single layer in inspector in unity, that I can then easily assign to gameObject.layer?

#

LayerMask allows multiple selection and is a bitmask

#

so not easily convertable

rigid island
#

just dont put 2 layers or it will break

wintry crescent
#

yea but that is not the ideal solution isn't it

#

goddamnit why isn't there a proper way

rigid island
#

well its the closest imo

#

I guess if you enjoy strings you can use that...NameToLayer

hexed pecan
#

EditorGUILayout.LayerField does it but I don't know if there's an attribute that makes an integer draw with it

rigid island
#

not type safe tho

wintry crescent
#

strings are even worse than a bitmask

wintry crescent
balmy plume
rigid island
hexed pecan
#

You could make a property drawer for it

rigid island
wintry crescent
#

I've seen it but thanks

#

I'm just devastated that this is still an issue in unity

rigid island
#

I guess. Layers and LayerMasks are different though so it makes sense

hexed pecan
#

Original question didn't have anything to do with layermasks though

#

There should definitely be a property attribute for drawing an integer as a layer dropdown

rigid island
#

i guess, but as of now, the layermasks just makes it easier to have all the layers in a dropdown already

ripe stream
#

i need help with my code, the code is maked by me i tested it but it doesn't normally work. now i need help from nice C# unity programers to make it working. This is a code of raft spawning (i am making game like raft but more realistic). This is a hard question for me, i am 4 days thinking and relizing how i can make normal raft spawning script but still not normally work.

tawny elkBOT
ripe stream
#

all nice working on main raft but when i walk example forward

hexed pecan
#

@wintry crescent ```cs
public class LayerAttribute : PropertyAttribute { }

#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(LayerAttribute))]
public class LayerPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
property.intValue = EditorGUI.LayerField(position, label, property.intValue);
}
}
#endif

Just add ``[Layer]`` on your int field to use it
hexed pecan
#

I'll need it too so thought I might as well make one 😁

ripe stream
steady bobcat
#

pretty sure there are a few other packages like this that have it too

hexed pecan
#

That apparently supports string fields

wintry crescent
steady bobcat
#

Ha yea there are too many variants of this kinda thing

wintry crescent
#

it has other cool things though, for what it's worth

#

the fact unity doesn't have a layer type built-in is a disgrace after so many years

#

I remember struggling with it in my first projects in unity 5

ripe stream
#

Osmal can you help me?

hexed pecan
#

In the bottom of the dropdown list

steady bobcat
#

huh guess they did a custom one?

hexed pecan
#

Yeah they dont use layerfield at all for some reason

#

I thought maybe it didn't exist back then, but it's been a thing for a long while

steady bobcat
#

maybe for string and int support

stone rock
#

I am currently looking into downsampling the depth texture into a texture with mip maps enabled. so to generate a depth texture where each mip is a downsampled version of the previous mip. I notice you can't read from one mip and write to a different mip at the same time, is that correct?

cursive moth
#

please @ me if you are able to help

hexed pecan
cursive moth
#

but so far, it looks like I'll have to go with the custom inspector

keen pier
#

can anyone tell my why my player shows up perfectly fine before respawning, but after respawn the player's sprite disappears in game? it still shows in the scene tab, but in the game tab it only shows the background, platforms, and the point light that is attached to the player. i set the respawn point's z position to 0, is it supposed to be in front of the scene? the project is a 2d platformer if that's of any use.
here's my respawn script:

public class Respawn : MonoBehaviour
{
    public GameObject player;
    public Transform respawnpoint;
    public Camera view;

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            player.transform.position = respawnpoint.position;
            view.transform.position = player.transform.position;
        }
    }
}
somber nacelle
#

your camera is too close to the player on the Z axis so it cannot render it.

#

obligatory: use cinemachine to control the camera

keen pier
#

thank you!

neat torrent
#

im trying to use my microphone but whenever i click play it is SO bitcrushed?

`` void microphoneToAudioClip()
{
string microphoneName = Microphone.devices[input];
microphoneClip = Microphone.Start(microphoneName, true, 20, AudioSettings.outputSampleRate);
_audio.clip = microphoneClip;

    _audio.loop = true;
    _audio.Play();
}

``
idk how to fix it can anyone help?

steady bobcat
#

do you know what the sample rate was for those past attempts?

neat torrent
#

is that in the project settings?

steady bobcat
#

I think so but if you have an audio file from a recording then you can see on that

neat torrent
#

thats the audio settings if that helps

steady bobcat
#

Try putting the sample rate as an int manually such as 44100 for 44khz

neat torrent
#

it just doesnt output now

#

oh actually it does but it still sucks

steady bobcat
#

if 44k is bad then something else is wrong

neat torrent
#

what else could be wrong?

steady bobcat
#

as the docs say, did you check the sample rates supported by the microphone device?

neat torrent
#

the cap is 48000

#

and its still very bit crushed?

twilit gull
#

what's the best way to setup a two-character system (like genshin or hsr)

#

should I have two meshes with animations and render them based on which one is being requested?

steady bobcat
neat torrent
steady bobcat
glacial gull
#

Hello, is it possible to move the cursor position through code on webGL? It seems like Mouse.WarpCursorPosition works fine on desktop platforms but not on webGL.

steady bobcat
#

I presume no web browser allows a page to manipulate the cursor so you may need your own virtual cursor

glacial gull
steady bobcat
glacial gull
#

Ok, thanks

deft timber
#

Use virtual mouse

wintry gust
#

Hey all, I'm having a little trouble figuring out how to add renderers LOD Group from script. I'm working on a modular character where the base mesh is using 4 LODs. I'd like to add my clothing to each of these LODs.

var renderers = clothingLodGroup.GetLODs()[i].renderers;
                    
// Combine the current renderers with the new renderers
var combinedRenderers = new List<Renderer>(baseLODs[i].renderers);
combinedRenderers.AddRange(renderers);

// Assign the combined list back to the LOD
baseLODs[i].renderers = combinedRenderers.ToArray();

I have this, looping through all the LODs, combining the renderers to one array and inserting the new array back in. But this does not seem to do anything.

mossy snow
#

GetLODs() is probably returning a copy of the LOD array

#

hold a ref to it, modify the ref, assign it back

wintry gust
dawn nebula
#

Let's say I have an item that can cycle between 10 different sprites depending on the state of the item. How would you go about setting up the swapping between the sprites? Surely not 10 different slots in the inspector. Maybe a Scriptable Object to hold them?

lyric veldt
bleak garden
cosmic rain
lyric veldt
#

it was just becuase that i accidently connected a few wrong

#

animations

#

i thought it was a code problem

stable osprey
# lyric veldt

You might wanna make use of Blending Trees -- you're duplicating states right now (like Idle/Falling_Idle and Running/Running_Backward)

lyric veldt
#

i should probably learn it

#

also

#

but also my character is

#

clipping through my camera

dense tinsel
#

!code

tawny elkBOT
dense tinsel
#

hi im having a hard time finding unity 2d frustum culling on youtube
i got this very rough script that i think needed heavy improvement but dont know where to start

using UnityEngine;

public class FrustumCulling : MonoBehaviour
{
    [SerializeField] private Camera playerCamera;
    [SerializeField] private GameObject[] CullingObjectsParent; 

    void FixedUpdate()
    {
        float cameraHalfWidth = playerCamera.orthographicSize * ((float)Screen.width / (float)Screen.height); 
        float cameraRight = playerCamera.transform.position.x + cameraHalfWidth;
        float cameraLeft = playerCamera.transform.position.x - cameraHalfWidth;
        float cameraTop = playerCamera.transform.position.y + playerCamera.orthographicSize;
        float cameraBottom = playerCamera.transform.position.y - playerCamera.orthographicSize;

        foreach (GameObject parent in CullingObjectsParent)
        {
            if (parent == null) continue;
            
            foreach (Transform child in parent.transform)
            {
                Renderer objRenderer = child.GetComponent<Renderer>();
                if (objRenderer != null)
                {
                    Bounds bounds = objRenderer.bounds; // get sprite bounding box
                    float objLeft = bounds.min.x;
                    float objRight = bounds.max.x;
                    float objTop = bounds.max.y;
                    float objBottom = bounds.min.y;

                    // check any part of sprite in camera view
                    bool isInView = (objRight >= cameraLeft && objLeft <= cameraRight && 
                                     objTop >= cameraBottom && objBottom <= cameraTop); 

                    child.gameObject.SetActive(isInView);
                }
            }
        }
    }
}

craggy veldt
#

rolling your own culling system would rarely be more performant than Unity's
any reason why? I'm guessing for instanced stuff?
if it is, you may want to offload them to a dedicated thread (non-mainthread). Even for simple AABB intersection test it can easily kill your game's perf

dense tinsel
#

if anyone know any good public script for this purpose i would be a verry ahppy boy

cedar wasp
#

I also wouldn't trust checking bounds for re-activating the object. I'm not sure if the bounds get recalculated if the object is inactive, when it's Transform changes (for example, it gets scaled).

mild goblet
#

i'm having issues adding a git url to the package manager. online people say to add the git.exe path to System Environment Variables. but my latest setup of Git doesnt even have a git.exe. it has the following.

steady bobcat
steady bobcat
mild goblet
#

i managed to get it working! the image i sent isnt actually the git.exe that the SEV Path was looking for. it was here:

C:\Users\jacgu\AppData\Local\GitHubDesktop\app-3.4.16\resources\app\git\cmd

one day i'll wrap my head around git

steady bobcat
#

github desktop is a GUI program FOR git

mild goblet
#

okay will do but i actually used that setup

steady bobcat
#

then add the correct git installation to your PATH

mild goblet
#

so where is the git your are reffering to

steady bobcat
#

mine is C:\Program Files\Git

mild goblet
#

will give it a shot

steady bobcat
#

well then /bin folder

#

for clarity: "C:\Program Files\Git\bin\git.exe"

mild goblet
#

yep i'm not sure if i need to include the git.exe

#

didnt need to

steady bobcat
#

just the folder that contains it

mild goblet
#

thanks for your prompt assistance rob

steady bobcat
#

np 👍

crisp flower
#
        {
            // Get the correct angle (this is confirmed correct!)
            float angleLabel = -(i * sectorAngle) - (actualSegmentAngle / 2f) - halfGap + globalRotationOffset;
            float radians = Mathf.Deg2Rad * angleLabel;

            GameObject spawnedImagePart = Instantiate(imagePrefab, radialPartCanvas);
            RectTransform childRectTransform = spawnedImagePart.GetComponent<RectTransform>();

            // Ensure pivot is correct
            childRectTransform.pivot = new Vector2(0.5f, 0.5f);

            // Calculate the exact position based on the correct angle
            Vector2 offset = new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)) * radialMenuObject.centerDistance;
            childRectTransform.anchoredPosition = offset;

            // Make sure the image remains upright
            spawnedImagePart.transform.localEulerAngles = Vector3.zero;

            // Apply correct scale
            childRectTransform.localScale = Vector3.one * radialMenuObject.imageScale;

            // Attach text and adjust position
            TextMeshProUGUI childText = childRectTransform.transform.GetChild(0).GetComponent<TextMeshProUGUI>();
            childText.rectTransform.anchoredPosition = new Vector3(0f, radialMenuObject.textVerticalOffset, 0f);
            childText.text = radialMenuObject.entries[i].text;
            childText.color = radialMenuObject.radialText;
            spawnedLabelParts.Add(spawnedImagePart);

            // Debug: Draw red lines
            Debug.DrawRay(radialPartCanvas.position, Quaternion.Euler(0, 0, angleLabel) * Vector3.up * 2f, Color.red, 5f);
        }```
#

I have a radial pie menu I'm workig on, and for some reason I just can't get my images put in the exact center of each slice. I have red debug lines that correctly cut through the center of the pie whatever the number of the parts, but the placed position of the imagepart seems to be "rotated" around different amounts depending on the number of entries. It must be something obvious can anyone slap me in the face with it?

crisp flower
#

here is an image of what the above outputs

steady bobcat
#

are you saying you want the image to be in the "center" of the green marked segments?

leaden ice
#

anyway why do you use different logic for the red lines as for the image position?
Vector2 offset = new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)) * radialMenuObject.centerDistance;
vs:
Quaternion.Euler(0, 0, angleLabel) * Vector3.up * 2f

dusk locust
#

These autogenerated files keep popping up. Does anyone know if I can/should just add these files to git-ignore?

crisp flower
# leaden ice anyway why do you use different logic for the red lines as for the image positio...

so the red line does cut through the blue pie chunk perfectly in the middle of the chunk (it takes into account the gaps between the segments. . There is actually a little white dot on the middle of the white texts which represents the origin of that label.

the intention with this
Vector2 offset = new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)) * radialMenuObject.centerDistance;
was to get a 2d offset position that matches the angleLabel so that the position of the of label is centered in the slice. But it just seems to change with the number of parts anyway..

crisp flower
#

(essentially trying to get the white dot on the red line)

hexed oak
#

are there any guides to integrating 3rd party scripts? I have inherited a project that has 150 scripts that all need to be tested/merged in

knotty patrol
#

Hey I'm trying to create a pick up system in dots and the way I do that is I have an Entity of an item lying in the world and when I pick it up it destroys it and adds it's prefab entity to the inventory. The problem is after it destroys the entity that was lying around in the world the prefab entity isn't working because it's referenced to the destroyed entity
does anyone know how can I solve this?

vagrant blade
knotty patrol
#

oh thanks my bad

minor swan
#

Like if they’re c# and built for unity just paste them into ur project and reload unity

minor swan
#

Everything else ur probably fine but im not 100% sure

swift falcon
#

started making a game that im gonna make possible to play in both singleplayer and multiplayer, have multiplayer sorted but am now wondering. When making my game, do i need to make different assets for singleplayer and multiplayer, with only the multiplayer ones having network object and transforms, or do i make the one player a host, or just how to handle differentiating between the two

vestal geode
swift falcon
#

👍

#

so just make it like its always a multiplayer game and it should be fine?

fiery steeple
#

Does anyone know how to solve this issue please ? It appears everytime I press Play, even thou I'm not using PlasticSCM so I guess it's maybe one of the assets I downloaded from the store that does that ? 🤔

rigid island
fiery steeple
#

(Removing Version Control Package)

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

public class Barricade : MonoBehaviour
{
    public GameObject Player; //Reference to the player object
    public GameObject QuestionPanel;
    public GameObject barricade;

    public Text pressE;
    private bool playerOnBarricade;
    public Text questionText;
    public Button closeButton;
    public InputField Q1;

    //Q&A
    private string question;
    private string correctAnswer;

    //Points
    public Text pointText;
    private int points;



    // Start is called before the first frame update
    void Start()
    {
        pressE.enabled = false; //Hide the text at the start
        QuestionPanel.SetActive(false);
        closeButton.onClick.AddListener(closeQuestion);
        Q1.onEndEdit.AddListener(checkAnswer);

        //Points
        points = 0;
        addPointsText();
    }

    // Update is called once per frame
    void Update()
    {
        if (playerOnBarricade && Input.GetKeyDown(KeyCode.E))
        {
            showQuestion();
            Debug.Log("Question Opened");
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            playerOnBarricade = true; //Player is on the key
            pressE.enabled = true; //Shows the key
        }
    }

  ``` my points only go up to 10 points and stops updating after the first barricade is answered.
#
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            playerOnBarricade = false; //Player not near the key
            pressE.enabled = false; //Hide the key
        }
    }

    void showQuestion()
    {
            QuestionPanel.SetActive(true);
            questionText.text = question;
            Q1.text = "";
            Q1.ActivateInputField();
        }
 

    void closeQuestion()
    {
        QuestionPanel.SetActive(false);
    }

    void checkAnswer(string answer)
    {
        if (answer == correctAnswer)
        {
            addPoints(10);
            removeBarricade();
        }
        else
        {
            Debug.Log("Wrong Answer");
        }
        closeQuestion();
    }

    void removeBarricade()
    {
        barricade.SetActive(false);
        Debug.Log("Removing barricade: " + barricade.name);
    }

    public void SetQandA(string newQuestion, string newAnswer)
    {
        question = newQuestion;
        correctAnswer = newAnswer;
    }

    void addPoints(int amount)
    {
        points += amount;
        addPointsText();
    }

    void addPointsText()
    {
        pointText.text = "Points: " + points.ToString();
    }

    private void OnCollisionEnter2D(Collision2D collision) //If player hits Barricade it cant go thorugh and prints Wall Hit to the console 
    {
        if (collision.gameObject.tag == "Baricade")
        {
            Debug.Log("Baricade Hit");
        }
    }
}
#

Im not sure why it only goes to 10 points

lean sail
tawny elkBOT
lean sail
#

that also does look like a #💻┃code-beginner question. you should add more debug logs or use the debugger to see whats happening exactly. Like see the value when you're adding points or if that method is being called at all

hidden canopy
#

Ok thanks

naive swallow
somber nacelle
#

so I personally would do the one Enemy component that then reaches out to your other components for different things when necessary. But instead of designing your other components to be "enemy specific", make them reusable by other objects. for example, do you really need a specific component for enemy health, or can it just be a "Health" component? because lots of things could have health besides just the enemies

#

okay well it seems you're already on the right track, just do that for movement and combat related components too

#

sure, you can use an interface to communicate between the components, but i'm saying to create components specifically for the types of movement and combat you want so you can modularize the enemies. so one enemy could have a WalkLeftAndRight movement component and another could have a FlyStraight movement component (using goomba and bullet bill movement as examples)

lean sail
#

for a loot system, you could most likely make 1 class for that and use the inspector to handle any differences between enemies. Unless you plan to have functional differences, stuff like amount of loot, rarity, etc, can all be handled by just plugging in data.
As for your movement question, id try to avoid having like a EnemyNameMovement or similar. You'd wanna unify the goblin movement between anything that walks in the same way, so that code could apply to other creatures

somber nacelle
#

well zelda was made in an entirely different engine. modularized components is the Unity Way™️ because the engine was designed with the component pattern in mind

#

okay that's cool. and i'm saying that because zelda was made in a completely different engine that just because it may do something one way, does not make it the right way to do something in unity. unity was designed in such a way that you would create components for individual behaviors and mix and match relevant components to compose your objects

#

if you try to fight against that then you're just going to have a bad time in actually using the engine

lean sail
#

Well something else can disable and enable movement which "removes" the dependency. But you might just be overthinking this. I say "removes" because no matter what you do, your components depend on each other at the end of the day. Moving the dependency just changes which object is gonna call GetComponent or be assigned a value in inspector.
To give an example, lets say an enemy has an ability and becomes invincible during this time. In some way, whether it be directly or calling some character method, it has to eventually call a method to be invincible

#

This is just how games work. You can go the full SOLID path but it just becomes a pain to work with. The first pain already being interfaces. By default you cant reference something like IHealth in inspector

signal moon
#

Hi. I have following functionality: I have chesspieces, that are supposed to dismember upon death. The problem is that the pieces (of the pieces xd) are not gaining the material of the original piece. For example, if black pawn dies, the shards it spawns are still white. Can't i do it by code somehow?

lean sail
#

for abilities sure, but if you're talking about EnemyMovement, EnemyHealth, EnemyVisuals then you likely could just code each as 1 class where the difference is what you assign in inspector. I see no reason why they need to be enemy specific. The example you gave for an enemy with multiple health bars could make sense to split into a separate class but thats not really unique per enemy. That's reusable for a category of enemies

lean sail
signal moon
#

if you could give me a keyword or link, i would be grateful

lean sail
#

Just as an example, for health, whats the difference functionally between a players health and an enemies health? Both probably have a current and starting health. Both would subtract or add to their health when whatever situation happens.
The only difference could be stuff like their starting health. This doesn't require a unique class for player/enemy when you just need to change a value in inspector

signal moon
#

Ok, i think i mostly get it. Thanks!

#

Im going to try it right now

naive swallow
#

None of that is fundamentally different, this all seems like "Number can go down, and notify some other scripts that my number went down"

lean sail
#

player can't die, they only get knocked unconscious
this isn't a functional difference, this is just language. something happens when their HP hits a threshold. The tutorial part could be a bool

#

enemies being stunned while the player cant is also just a bool

naive swallow
#

It's not about creating a monolith, it's about creating a hierarchy

lean sail
#

thats just an event

naive swallow
#

Enemy and Player would both extend some DamageableEntity script or interface

#

Has some OnTakeDamage and OnDie methods that can be overridden

lean sail
#

it sounds to me that you have a lot of repeated code trying to avoid this "monolithic class"

somber nacelle
#

and that stuff is a separate component from the actual Health. why should the Health component know what happens when something "dies"? it should only notify other objects that it has reached that point of "death"

naive swallow
#

Yeah that's probably fine, but you can probably add more to it

#

Defining events to call on damage/death, for one

lean sail
#

we could make up stuff to worry about all day, about any implementation you do. I think the thing you should actually worry about is repeated code
Literally the only if statements mentioned here was if the character should be invincible during the tutorial and if the character can be stunned.

#

and the stuff like what happens when the player hits 0 hp should be an event. that way you have 1 health class, and subscribers which do something based on the event. This is already separate classes
Otherwise you have multiple health classes with the exact same logic because a few of them want to call a seperate method. This is comparable to having different health classes because one of them wants to start with more hp

#

Then you wake up one day and suddenly decide enemies should die when they hit 0.1 hp to make a smoother experience (just making up something to stay in the health example). Suddenly you have to go edit every health class. This really isn't good

#

The difference being it's not repeated code anymore. It's also not a new component per object. Surely you'd have more than 1 enemy that dies in the same way like playing an animation and being destroyed

steady bobcat
#

this is a strange conversaion. virtual methods exist for this reason, to override behaviours but share others

lean sail
#

You should just take it case by case. I dont really know enough about the other variables and stuff like rocks to suggest much.

stark sun
steady bobcat
#

if you ever want a good example, source 2013 is all there to look at

#

but csgo leaked only 🤔
and tf2 was released in 2013 recently

#

dw im aware i do lots of stuff in the source community (worked on tfs2 for example)

lean sail
steady bobcat
lean sail
#

I mean yea you could look at every perspective of games that wasnt made in unity. It's not "harmful", it cant be since its learning. But the structure of what you make in unity is going to be different

steady bobcat
#

sbox which is based on source 2 has moved its design to be very unity like

#

they did? huh sounds strange

lean sail
#

Studying other projects can really just lead you down strange paths. And it seems you're already aware of how other games are structured.
Imo the best advice for you is literally tryitandsee with the suggestions above

#

You dont need to make the best structure, or follow SOLID all the way down. You need a game that runs at the end of the day. Every weird decision you see in a game is because the game needed to run and that's how they chose to do it

naive swallow
#

Is there any way to get JsonUtility to make a Json array without a name? I'm trying to generate data to send on a POST request but it always slaps the variable name in front of the string if I try it. I'd rather not just built the array by hand.

steady bobcat
#

tried newtonsoft json?

naive swallow
steady bobcat
#

well the json utility uses the unity serialisation system which probably isnt going to do all you need it to

#

and unity has a package maintained already for it

#

its valid

#

the ol' "ill improve it later" but later never happens

#

Where I work rn we have a shared libs package, i've added some useful things to it over past years

#

always wise i think to build a good base of useful stuff

steady moat
#

Beware of using too much interface. Healing/Attacking could make sense but GetHealth and GetMaxHealth might become an issue if you have a considerable amount of "Statistic".

Also, instead of using "setOnFire", "canAlertNearby", etc. you might want to use something else. Otherwise, if you have a lot of "Really Specific" behaviour, you will have a really, really long and non cohesive damage info class.

Obviously, it all depends on the depth you are looking for. If you do not believe you will scale more then that, it is way better to keep it simple as you do.

steady bobcat
#

and you 😎

steady moat
#

It is not uncommon to have a lot of "Statistic" in a more RPG still games. You might find yourself with more generic statistic such as health, armor, mana, etc. and more specific statistic such as Ability Damage, Trap Damage, Empowered Damage, Poison Resistance, Working Speed, etc. and it quickly become out of hand if every type of statistic is hiding behind an interface. The best way is to use composition instead.

#

By example, instead of accessing the health of a given object by doing:

object anObject = ...;

if(anObject is IHealth)
  ...

You would do:

Entity anEntity = ...;

if(anEntity.TryGet(...))
#

The advantage is that it scale really well an you can even easily define statistic purely as data if you have a system that read/use any statistic.

#

Yes, in the sense of statistic this amount of flexibilty is justified.

#

Usually, it makes thing harder to work with given that you loose the "Type" of each class.

#

No worries, as I said, it is better to keep what you have if you do not expect any explosion of statistic.

#
  1. If you keep what you have, at some point you might find yourself with a lot of parameters.
    setOnFire seem to be a really specific an arbitrary effect for a given attack. I expect that you might have a lot of such effect in the futur.
  2. If you keep what you have, you will most likely get into situation where you need multiple parameter for a given effect.
    By example, setOnFire might require the duration, the damage, the intensitity, etc...
#

But, again, if it is not the case and there is really a limited amount of effect an attack can take do not bother doing anything elaborate.

#

Composition again.

public struct DamageInfo
{
  public DamageInfo(List<Effect> effects ...);
}
#

Obviously, it come with a cost if you do not cache and do not use a data-oriented approach.

#

Not really, it is polymorphism in this case.

#
public class SetOnFire : Effect {
    public override void Apply(...);
}
opaque vortex
#

So is it possible to have a function not apart of my job system burst to run at the same time the burst does? My issue is the function that is supposed to work during the time the burst is on in the main thread never is synchronous to the burst.

Is there ways around this?

#

Okay

steady moat
#

You can add a CanBeApply or a simply returning if you detect the effect should not be applied.

#

If you combine both solution I said earlier, you could easily see something like:


public class SetOnFire : Effect {
    public override void Apply(Entity entity) {
      if(entity.TryGet("FireImmunity", out bool fireImmune) && immuneToFire)
         ...
   }
}
#

It could be the first one or the second, but ideally you would use composition instead or at least an interface.

#
class SetOnFire...
bool CanApply(obj)
   if (obj is ICanBeSetOnFire)
      return false;
   return true;
#

I know where you are coming from, having most of the data be non typed can quickly become out of hand.

#

Oh, if you mean having something like a string to access the statistic ? Obviously this is bad, but it is the easiest to write. You usually, you might want to associate meta data to each statistic (icon, name, description, etc) hence they all have a ScriptableObject associated. Whenever I want to access the statistic, I use the ScriptableObject.

#

It has the down side that some of the statistic might not have any need of a visual representation but I live with it.

#

Yes.

#

Something like:

public class StatisticDefinition : ScritableObject 
{
  [SerializeField] string title;
  [SerializeField] string description;
  [SerializeField] Sprite icon;
}

#

And, if you need more meta data you can even inherit from it.

#

No, the StatisticDefinition is mostly data. Also, GetValue would not be a function of it.

#
public class SetOnFire : Effect {
    public override void Apply(Entity entity) {
      if(entity.TryGet(Statistic.FireImmunity, out bool fireImmune) && immuneToFire)
         ...
   }
}

public class Statistic 
{
    public StatisticDefinition FireImmunity => //Load and cached the ScriptableObject
}

#

To get the value, you still rely on the entity.

fiery spruce
#

i have spent 8 hours trying to make system.speech work, is it possible even? i hope theres some easy solution i just havent found

fiery spruce
random oak
warm badger
#

Hi, I am working on a kind of motorcycle controller... I am using rigidbody. No w I apply some forces at the center of mass while accelerating, this gives a realistic torque. Like tilting a bit backward when accelerating and tilting forward when braking. This tilting is visible on the bikes X axis. Now the problem is this cause a lot problems on the y and z axix(falls of, flips off etc)... Now when I freeze the Y and Z rotation, the x rotation doesn't happen naturally anymore. So what should I do to let the rigidbody control the X axis rotation as it gives realistic vibe but stop it from rotating y and z insanely?

cosmic rain
warm badger
sturdy hatch
#

I do not know how advanced / beginner this is, but I am a little lost.

I got this code: https://pastebin.com/fWCyXsRg

It's my CameraController, everything functions perfectly. The only issue I got is.. the cameraAdjustSpeed should handle how fast the camera adjusts. But even if I lower this, the camera snaps right back into place the moment I move, while it should gradually move back into place based on cameraAdjustSpeed set.

plucky inlet
quartz vessel
#

Hi, I'm using an RCC controller with Fusion, but I'm experiencing issues with network transform and replication. Additionally, I'm having trouble with the network controller, where both cars move when I press the buttons. Can anyone help me resolve these issues?

brave meteor
#

Hi! Please help me with the code, I am a novice developer in unity. You need to make a counter that will be replenished when a certain object is deleted.

cosmic rain
leaden ice
brave meteor
leaden ice
#

If you want help you need to share your code and your errors, and give a better explanation of what you're trying to do in the game

steady bobcat
#

derp wrong message

steady bobcat
plucky inlet
tawny elkBOT
#

:teacher: Unity Learn ↗

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

brave meteor
# leaden ice "gives me an error" is much too vague for anyone to help you with

In my code, I need +1 point to be added to the counter when a word is deleted. ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Score : MonoBehaviour
{
public static int scoreAmount;
Text scoreText;

void start()
{
    scoreText = GetComponent<Text>();
    scoreAmount = 0;
}
void Update()
{
    if (GetComponent<Word>() == null)
    {
        Score++;
    }
}

}```

leaden ice
#
  1. This logic is really confusing and most likely makes no sense
somber nacelle
leaden ice
#

What does it mean for a "word" to be deleted?

#

what's a word?

#

How are words being added/deleted/edited?

hard estuary
# brave meteor I did this, but it gives me an error, maybe I don't understand something because...

If you want to become Unity Developer, I would suggest following available tutorials step by step. If it's just a homework and you don't plan to master it, I would suggest the following approach instead:

  1. Open up ChatGPT.
  2. Describe your situation.
  3. Copy the exact error from the console and paste it into chat.
  4. Read what it responded and apply appropriate changes.
  5. If problem is not resolved, return to step 2. If you get stuck (ChatGPT can't come up with better solutions or starts writing stupid things), seek help somewhere else.

ChatGPT often writes stupid things, but it's more likely to write something useful if your problem is basic. Since you're beginner, your problems will be mostly basic. Remember: the more detailed your description is, the more likely you will be to get the correct answer. Otherwise, you'll only cause confusion.

vestal arch
plucky inlet
steady bobcat
#

plz dont make more "vibe coders"

vestal arch
#

following available tutorials step by step
just this part is plenty enough
they're quite brief
if you don't want to fully master unity, just don't go through the advanced tutorials

#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

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

vestal arch
#

this is plenty

hard estuary
vestal arch
#

ah yes, because problem-solving in general is not a useful skill at all

#

to be blunt; the majority of your message, and the part that's listed as steps, is about chatgpt. we really don't need someone coming in and seeing just that part and thinking it's a good idea for learning.

hard estuary
somber nacelle
vestal arch
#

problem solving is not topic-specific

#

problem-solving in an unfamiliar topic is a great way to actually practice problem-solving, actually.

#

especially when there's plentiful resources to help, which is definitely the case here

hard estuary
hard estuary
plucky inlet
#

You got your point, no common ground between individuals here, lets let go

hexed pecan
#

And the string has a weird scale

fluid crown
#

Parent rotation possibly

hexed pecan
#

And some rotation weirdness going on too yeah

stark sun
#

but it has to follow the midpoint of string so I child it to him

hexed pecan
#

Find another way. Don't have a non uniformly scaled parent

fluid crown
#

You can simply spawn it at tthat position instead of make a child

hexed pecan
#

It needs to follow the string when it's drawn though

somber nacelle
#

or use a position constraint component

hexed pecan
#

Constraint or manually moving it are your main options

stark sun
#

Okay I will try constraints thanks. UnityChanThumbsUp

tacit gale
#

Hi, I need a save system that will store the state of objects in the scene, including which objects were added, which were deleted, etc. Is there any recommended package for this, or what's the best way to create such a system?

shadow wagon
#

why does the invoke in GenerateNewMap show an error? the RoomGenerator is subscribed too it, so its odd for it to show an error

public class MetroMap : MonoBehaviour {
  public static event Action MapGenerated;

  void Awake()   {
    GenerateNewMap();
  }
  
  void GenerateNewMap()  {
    MapGenerated.Invoke(); // NullReferenceException: Object reference not set to an instance of an object
  }
}

public class RoomGenerator : MonoBehaviour {
  [SerializeField] MetroMap _metro;

  void Awake()   {
    MetroMap.MapGenerated += GenerateRoom; 
  }
  
  void GenerateRoom()
  {
  }
}```
somber nacelle
#

you invoke the event before anything is subscribed to it

shadow wagon
#

ah

somber nacelle
#

also you typically want to null check your events when you go to invoke them, you can use the ? operator to do so like MapGenerated?.Invoke();

whole sorrel
#

I'm trying to recreate what the SOAP asset does by Scriptable Variables that can be of different kinds, even lists. Note: I am not familiar with the specific implementation as I don't have the money to buy it (otherwise the problem would be solved) so I'm trying to recreate it on my own.

Following git-amend's tutorial I manager to get this script:

public class ScriptableVariable<T> : RuntimeScriptableObject
{
    [SerializeField] T _initialValue;
    [SerializeField] T _value;

    public UnityAction<T> OnValueChanged = delegate { };

    public T Value
    {
        get => _value;
        set
        {
            if (this._value.Equals(value)) return;
            this._value = value;
            OnValueChanged.Invoke(value);
        }
    }

    protected override void OnReset()
    {
        OnValueChanged.Invoke(_value = _initialValue);
    }
}

That can be easily extended via inheritance and allows me to create a generic list:

public class ListVariable<T> : ScriptableVariable<List<T>> { }

Now my question is how can I make the list generic? Because of course I cannot create a scriptable that has a list of value T, I'd need to either ask the user to specify the type on creation or create different specific lists, which is not very flexible I gotta say...

#region Specific Implementations
[CreateAssetMenu(fileName = "Game Objects List Variable", menuName = "SOAP/Variables/Game Objects List")]
public class GameObjectListVariable : ListVariable<GameObject> { }
[CreateAssetMenu(fileName = "Integer List Variable", menuName = "SOAP/Variables/Integer List")]
public class IntegerListVariable : ListVariable<int> { }
[CreateAssetMenu(fileName = "Float List Variable", menuName = "SOAP/Variables/Float List")]
public class FloatListVariable : ListVariable<float> { }
[CreateAssetMenu(fileName = "Bool List Variable", menuName = "SOAP/Variables/Integer List")]
public class BoolListVariable : ListVariable<bool> { }
#endregion

Am I missing anything?

shadow wagon
somber nacelle
#

it's not a "nullable type", because Action is always nullable being a reference type, this is the null conditional operator.
but anyway, you just need to invoke the event later than you currently are, such as in Start instead of Awake

shadow wagon
#

what I'm struggling with is getting the order of things correct. I keep using Awake/Start interchangeably which isnt ideal. I keep trying to work where some Awakes need to happen before other Awakes, and then some Starts have to happen before other Starts

#

the Map has to complete its generation, before the Room can be generated, then that has to happen before I allow anything to spawn

somber nacelle
hexed pecan
#

SerializeReference being the key here

#

Allows polymorhpism

shadow wagon
#

what would you suggest I do to ensure everything gets executed in the exact order I need? Events feel like the right approach, but I've felt sure of things in the past then later found that approach sucks

steady bobcat
#

Initialize components yourself as much as possible

#

I do this for basically everything

hexed pecan
whole sorrel
shadow wagon
#

so subscribe in Awake, invoke in Start?

hexed pecan
#

But I think you kinda get the idea

#

SRef is really powerful

whole sorrel
#

Thank you, I didn't know that library

hexed pecan
somber nacelle
whole sorrel
#

This is OP

late lion
hexed pecan
#

Ah yeah waasn't sure, thanks for clearing it up

steady bobcat
hexed pecan
#

Me who made my own drawer even though I know this exists 🧑‍💻

#

(I really just wanted to learn)

shadow wagon
#

even if two components share the same object, I'm avoiding a bunch of GetComponent calls like I usually do

steady bobcat
#

e.g. load level, await init + load, hide loading screen

plucky inlet
#

Hey everyone, I am trying to add a package dependency tarball file to my custom package. What is the correct path to fill in the package.json? Like would it be "file:../Library/PackageCache/com.mypackage/Packages or something? Not sure it belongs to coding, but it at least is a json file. Point me to another channel, if it fits better.

trim schooner
#

wouldn't you just put the package name?

#

com.mypackage.somepackage

plucky inlet
#

If I would import it throuigh packagename thats available in unitys registry, yes. But its a custom package for visionos from unity, which only is distributed as tarball, the heck why 😄

sullen zenith
#

Im currently working on a 2D roguelike, and made a prototype for handling active-use items - but before I move on, I wanna check if there's a more efficient way to go about this

I basically made an Item class, and from there I made a TNTItem script so I could make a scriptable object and use that? But it seems off because this would gradually be cluttered

steady bobcat
#

a normal folder in there thats a package will be.

plucky inlet
steady bobcat
#

err what

shadow wagon
#

whats going to be tricky is getting the process to begin again once I need to load the next room. I've done it a few different ways but each time it feels like it introduces problems when I need to get the next room after one has already been created

steady bobcat
#

OH GOD IM STUPID I JUST REALISED

plucky inlet
hexed pecan
steady bobcat
#

Now i understand, i think you would just have the package id dep but ofc how is the package manager meant to auto get this dep? it cant so i guess it just wont?

hexed pecan
#

So are you only generating the rooms next to the one you are currently in?

whole sorrel
#

@hexed pecan maybe I'm reading this incorrectly but with SerializeReferenceDropdown, don't I still need to give the list a type?

steady bobcat
#

git packages cannot have other git packages a deps so im gonna say unless the user installs the tar dep manually before it will just shit the bed @plucky inlet

whole sorrel
#

That still doesn't fix the issue of the scriptable not being instantiable

shadow wagon
plucky inlet
hexed pecan
steady bobcat
plucky inlet
steady bobcat
#

tbh im not sure what unity does when you install a tar package via the gui

somber tapir
# sullen zenith Im currently working on a 2D roguelike, and made a prototype for handling active...

It's one way, but as you already noticed it's not really efficient since you only create 1 instance for each SO.
A better way is to have an SO for a generic item and the effects (or whatever makes the TNT different) be a field which can either be another SO or a plain C# class.
You would need to have a way to serialize those, like this package does: https://github.com/mackysoft/Unity-SerializeReferenceExtensions

Here is what a SO looks like for me:

plucky inlet
sullen zenith
#

I see, ill try it out. Thanks

whole sorrel
plucky inlet
steady bobcat
#

isnt that good, its installed now?

plucky inlet
#

no, thats when I import it right away through packagemanager. Thats not when I import it as a dependency of my package

#

In that case, it would be in the dependency array of

 "com.unity.services.vivox-visionos": "file:./Packages/com.unity.visionos.vivox.unityVisionOsSdk-16.5.4.tgz",
#

But that gives me: Version 'file:./Packages/com.unity.visionos.vivox.unityVisionOsSdk-16.5.4.tgz' is invalid. Expected a 'SemVer' compatible value.

#

and semantic versioning is not working in that case, so im out of ideas 😄

steady bobcat
#

yea the value should be the version not some path to a file?

#

the dependencies are only package id and a version

plucky inlet
#

Yeh, thats why I wonder, where the heck do I put it if possible at all

shadow wagon
steady bobcat
shadow wagon
plucky inlet
steady bobcat
plucky inlet
#

I am actually testing it right now to just throw it with the number

steady bobcat
#

where I work we have our own packages hosted on jetbrains spaces for our internal packages

plucky inlet
#

expected: com.unity.services.vivox-visionos (dependency): Package [com.unity.services.vivox-visionos@16.5.4] cannot be found

#

yeh, hosting on a custom server would be the other option, for sure

steady bobcat
#

you can see if this is on open upm too but otherwise you can just inform users to install vision os first

plucky inlet
#

well, so somehow i gotta force the user to add the tarball file for now, from wherever, because unity does not provide any other form yet

steady bobcat
#

in the gui its doable and the error hopefully is good enough to remind them that this must be done first

plucky inlet
#

Yeh, not very convenient tho and I wish, there was another way. But maybe, they include the visionos part in the global registry some day or at least make an actual package in their registry out of it. Thanks tho for your time and suggestions! 🙂

steady bobcat
#

np, ive fucked with packages a bit but shame it cant do this. At least we have the package manager at all 🦾

zinc parrot
#

If I have a gameobject with a script attatched to it, with the script containing a bunch of float[], int[], etc.(used for saving data local to that gameobject basically)
but now I want to replace those float[] and int[]'s with a structure as:
struct[] NewData;
where NewData instead contains those float and int arrays
is there an easy way to tell unity to transfer that data from the old arrays to the new array of structs?

late lion
#

It means you have to keep the old fields around, but you can make them private and mark them as obsolete to ensure they never get used.

late lion
#

This approach is ideal if you are making a plugin used by others. But if it's just your project, you can always go in and edit the scene or prefab files directly.

zinc parrot
zinc parrot
#

trying to understand how this works and how I should use it

zinc parrot
#

thanks!
Do I probably wanna do it in OnBeforeSerialize or OnAfterDeserialize?

#

ah probably onbefore

late lion
zinc parrot
#

ah ok!

#

does this run before or after OnEnable?

cold parrot
zinc parrot
#

ok

cold parrot
#

it runs before awake even

zinc parrot
#

oh wow

low rapids
#

` private void Update()
{

 Vector3 worldPosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);

 transform.position = worldPosition;

}
`
This script is supposed to make the Cursor go to the mouse Position. This Works, however the Cursor goes to the same X axis as the Camera, which results in the cursor not getting rendered. What can i do? im using cinemachine

fiery geyser
#

how do i fix the error: RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same, when running Unity ML Agents? oh, and unity editor also likes to freeze after a bit it runs same for the built game

late lion
# zinc parrot trying to understand how this works and how I should use it

Here's an example of how to use it.

public class SerializationCallbackScript : MonoBehaviour, ISerializationCallbackReceiver
{
    [SerializeField, Obsolete]
    private float[] floats;

    [SerializeField, Obsolete]
    private int[] ints;

    public MyStruct[] NewData;

    void ISerializationCallbackReceiver.OnBeforeSerialize()
    {
        // This can be empty, or you can make sure the old fields are definitely empty.
        floats = null;
        ints = null;
    }

    void ISerializationCallbackReceiver.OnAfterDeserialize()
    {
        if (floats.Length > 0 || ints.Length > 0)
        {
            // Convert to struct.
        }

        // Clear the old fields to avoid duplicate data.
        floats = null;
        ints = null;
    }
fiery geyser
late lion
#

I made the interface implementations explicit, so you're not adding new public methods to a script others might be using.

zinc parrot
late lion
zinc parrot
#

yeah

late lion
#

But it's fine to make them private and add [SerializeField] for this

zinc parrot
#

sweet

#

they were [serializefield] public

hexed pecan
#

For personal projects where you don't need to worry about backwards compatibility or such, can you get rid of the old fields after you have reserialized once?

somber nacelle
late lion
#

You can even go as far as renaming them and use [FormerlySerializedAs] to make it more clear they are not to be used.

[SerializeField]
[FormerlySerializedAs("floats")]
private float[] floats_OBSOLETE;
earnest fern
#

does anybody here know how to make my character controller jump continuesly while HOLDING spacebar, using the new input system?

#

I already have the code for jumping and I have a jumping cooldown

late lion
dense fog
earnest fern
#

I just want my character to continuesly jump while HOLDING the button

late lion
hexed pecan
#

Yeah, I'm just wondering

zinc parrot
late lion
late lion
# zinc parrot heck

I was about to say, ISerializationCallbackReceiver can be called in a background loading thread, so you can't access most Unity APIs.

earnest fern
zinc parrot
#

heck

hexed pecan
#

With CC, you would apply the jumping velocity every frame in Update when the jump key is being held

late lion
zinc parrot
#

ooo ok

hexed pecan
#

Ah yes, the internal awakening

hexed pecan
#

Or maybe im not understanding it

earnest fern
late lion
hexed pecan
#

Most other physics related stuff goes into FixedUpdate though

earnest fern
#

so I don't need to modify my existing jump method?

hexed pecan
earnest fern
#

oh

#

that feels like it's the noobest question ever, sorry

#

I'm really new to game dev

hexed pecan
#

It depends. You can show your !code

tawny elkBOT
earnest fern
#

and call it in Update

#

if it's not there already

placid lagoon
#

can someone program me a mobile button that if you click it a sound plays please @somber nacelle no i didnt learnd for that or something i tryed to do it myself but i dont understand it

vestal arch
#

break that down in to separate portions

#

how to make a button, how to play audio

languid hound
#

People have given you direct steps and resources for learning