#archived-code-general

1 messages · Page 375 of 1

cobalt bloom
#

oh I found something in the graph settings

#

'Fragment Normal Space'

#

now its no longer gray

#

but it doesn't look fixed either

stone pewter
#

ah yeah I was about to post that

maiden fractal
#

Like this, just put the corners on top of each other. Each corner needs 3 vertices with different normals, otherwise the normals will look like in the second picture and end up interpolating into a smooth edges which doesn't seem to be what you were looking for

cobalt bloom
cobalt bloom
#

Hopefully at least.

stone pewter
#

..I thought you two were the same person for a good like 5 minutes

cobalt bloom
#

lmao

stone pewter
#

I'm guessing it might not be

cobalt bloom
#

yes it is

#

On the other side there seems to be random dots?

wind ridge
#

i don't want hard edges, i just don't want it to tile like it is rn

maiden fractal
#

You don't?

cobalt bloom
#

Are you using mesh.RecalculateNormals(); after Mesh generation?

stone pewter
#

because your screenshot looks the way it does presumably because each voxel is a cube with 8 vertices, sharing normals in the corner, which leads to the rounded shading you're seeing on every voxel

wind ridge
stone pewter
#

right, that's because of what I just wrote above c:

cobalt bloom
#

They mean that the lighting is dark in places that it shouldn't be dark

cobalt bloom
stone pewter
#

yeah that's what I wrote lol

cobalt bloom
#

The way my voxels were initially rendering is what griff is trying to get, and what I'm trying to get the opposite of.

stone pewter
#

oh no now I'm confused

#

who wants what now

wind ridge
cobalt bloom
#

Just, don't set normals when generating the vertices

#

also are you culling faces that are obstructed by other voxels?

stone pewter
#

well, that depends on how you want to shade it, you'll have to supply normals one way or another

cobalt bloom
#

After mesh generation is complete, do mesh.RecalculateNormals();

stone pewter
#

and doing in in the vertex data is one way, and doing it in a shader is another way

wind ridge
wind ridge
stone pewter
cobalt bloom
#

I believe it doesn't work for griff because they do not cull faces.

stone pewter
#

yeah

cobalt bloom
#

It should fix itself when you cull faces, however the voxels would look off unless they were far away from the camera so I recommend a different approach

wind ridge
stone pewter
#

it'd kinda just be a neighbor check

cobalt bloom
#

Marching cubes isn't for culling internals...?

#

Its to smooth a voxel surface.

stone pewter
#

if two adjacent voxels are solid -> don't create a face between them

cobalt bloom
#

^ That's basically what my approach is.

wind ridge
cobalt bloom
#

What do you mean by that?

stone pewter
#

marching cubes is a more specialized tool to discretize volumetric data, but your data is already discrete, there's no need to use marching cubes

wind ridge
stone pewter
#

marching cubes is a way to generate a polygonal surface from a description of arbitrary solid volumetric shapes

cobalt bloom
#

Its basically a method to make a smooth surface from voxel data.

#

As far as I can tell

wind ridge
#

ah so nothing like what i want lol

dusky lake
# wind ridge idrk, nobody online has explained marching cubes decently that i've seen, not su...

In this coding adventure I try to understand marching cubes, and then use it to construct an endless underwater world.

If you'd like to support this channel, please consider becoming a patron here:
https://www.patreon.com/SebastianLague

Project files:
https://github.com/SebLague/Marching-Cubes

Learning resources:
http://paulbourke.net/geometr...

▶ Play video
stone pewter
#

it's a way to make a discrete polygonal surface from smooth volume data

cobalt bloom
#

Really?

stone pewter
#

like, say, turning a sphere volume into a mesh surface, you can use marching cubes for that

#

or surface nets, is another similar technique

#

(I suppose the volume data doesn't have to be smooth but yeah same same. straight lines are called curves in math so what are words even)

native lark
#

Did someone know here something about motion blur (post processing)

sleek bough
#

don't cross-post

native lark
#

Yeah but no-one is writing there

wind ridge
dusky lake
# cobalt bloom Really?

Yes, it samples a float value and only displays "edges" (very simplified) when reaching certain breakpoints, making a smooth surface polygonal

The missconception that it makes voxel -> smooth comes from the fact that you can also feed it with less detailed data and still get a result (and that its used by many to do this exact task)

dusky lake
#

not sure what exactly you need

cobalt bloom
#

Still have no idea how to calculate normals in the fragment shader. None of the methods I'm finding online work on Unity.

stone pewter
#

anyway if you want to make a voxel/minecraft style world, you won't need marching cubes

wind ridge
stone pewter
#

try making it from the lit SG template

dusky lake
wind ridge
dusky lake
cobalt bloom
dusky lake
stone pewter
dusky lake
#

looks like its sharing the vertex and that breaks the normal of it

dusky lake
#

4 per side

cobalt bloom
#

wait is there a difference if I swap them

dusky lake
#

otherwise you break normals

wind ridge
#

i'll try the 24 vertices, but that seems like itd be really slow

stone pewter
#

(unlike the dot product where order doesn't matter, bc it's commutative)

cobalt bloom
#

bruh it works now

stone pewter
dusky lake
cobalt bloom
#

griff its not impossible to use 4 vertices per face even if you use only unique vertices

#

you can still make it look fine

#

with correct lighting

stone pewter
#

but that requires a custom shader

#

which might not be apt depending on your use case

cobalt bloom
#

btw there are some issues

dusky lake
#

that looks like doubled surfaces

wind ridge
dusky lake
stone pewter
cobalt bloom
stone pewter
#

I don't think it's doubled

#

I think the depth only pass in the shader (generated by SG) doesn't respect the custom frag shader normals with ddx/ddy

#

it might fall back to mesh normals

dusky lake
#

it looks like two surfaces sharing the exact same position and they are fighting over the renderer (which gets rendered on top)

cobalt bloom
#

so do I just make the mesh not have normals

stone pewter
#

pretty sure it's not z fighting no

cobalt bloom
#

normal fighting then

wind ridge
#

is there a limit on vertices in unity?

#

per object

stone pewter
cobalt bloom
#

what the fuck

#

I removed the mesh's normal (so now vertice data is just a position)

swift aspen
cobalt bloom
#

and now its all dots

stone pewter
stone pewter
#

and see how it behaves in both cases

cobalt bloom
#

IT WORKS!!!!

#

OH YES

swift aspen
#

congrats 😄

stone pewter
#

neat!

cobalt bloom
#

And I also have 2x less vertices than if I don't use unique vertices

#

since without unique vertices its around 7500 verts

#

with only unique vertices its less than 4500

#

so its quite nice

#

next I'll try to make the greedy meshing algorithm properly

#

since rn its just slightly better than naive meshing only because I do not have repeating vertices

stone pewter
#

is this mostly for learning or is there a specific use case/game style in mind?

#

because often the naive approach can be faster, especially if you expect to edit the mesh frequently

cobalt bloom
#

I saw the game 'Clone Drone in the Danger Zone' and wanted to make a similar game. It's basically a robot fighting game where the robots are destructible.

#

I checked the game code and they use a deprecated Unity asset called 'PicaVoxel' so I'm making my own voxel engine

stone pewter
#

alright

cobalt bloom
stone pewter
#

that's what I was thinking too

#

triangles and vertices are very cheap to render

#

the expensive part is generating them

#

so you'll want the generation part to be simple

cobalt bloom
#

btw I also already have collider generation so now I just have to add destruction and the system is basically already done

#

and because I expect most voxel objects to be super small, I decided to not use 'chunks' to cut the object into smaller sections as they are unlikely to be super large or anything like that anyway

stone pewter
#

you can probably speed this up significantly with the job system as well if you need to, without using fancy triangulation algorithms

#

it's a very parallelizable thing

#

or do it with compute shaders!

#

but that can be a lot to learn if you're not familiar with shaders

cobalt bloom
#

I can't really use compute shaders anyway because my laptop only supports OpenGL 3.1

#

It looks like the voxel objects are pretty performant th

#

I can generate a 20 voxels radius sphere's mesh and collider instantly

#

and my laptop is shit ass so anyone else is likely to not experience any lag

#

at a radius of around 40, the vertice count is more than the limit it seems like, tho.

#

So it probably can't work with any voxels too big anyway due to mesh size limitations

#

I feel like its pretty small tho

#

60k triangles and 69k vertices

#

Without any of the optimizations it should have like 3 times more vertices

#

with smaller meshes vertices are literally less than triangles

blazing tiger
#

I need a critique for an inventory data representation I made up. I will separate data from prefab, so there will be flaskData and flask prefab. flaskData will inherit from abstract itemData and hold additional properties, like the fluid contained as well as overriding methods, such as getting description to display what it's currently filled with

#

Does this make sense?

#

There will be a lot of code repetition though, ideally I'd like to find a way for a component to modify various evens with its data

#

For example, if we use composition, flask data class might have a fluidContainer field, but I'm not sure how can I make this field modify the string returned by description getter to append what kind of fluid it contains

cold parrot
# blazing tiger I need a critique for an inventory data representation I made up. I will separat...

To answer this you should explain the problem this data model must solve. What is the game-design it needs to support? What current and future constraints need to be considered, how does the data change? Any skill issues in the supporting team? Is tool development effort important, or does it have to use builtin inspectors? Who will configure and design the system, what is their technical expertise? Does it need to be saved/restored and when/how? Does it have to be networked?

cobalt bloom
#

How would I use the Job system here? I want to multithread collider and mesh generation.

cold parrot
cobalt bloom
#

What additional information is required?

#

UpdateMesh(); updates a list of meshes that is looped through every frame and rendered used Graphics.DrawMesh

#

UpdateCollider(); deletes a bunch of BoxColliders and generates new ones based on voxel data.

#

I'm guessing I'll have to generate the BoxCollider boxes on another thread then create the boxcolliders on the main thread, and for the mesh, I'd have to send the meshes to the main thread after all generation is complete, so probably not much changes

blazing tiger
#

So it is mainly for replication and saving. Potentially it might be used for modding in the future, but this isn't a concern at the moment

#

Moreover, right now all item data is just a bunch of gameobjects, and sometimes it's a hassle to manage. I think it would be better so separate data from representation anyway

cold parrot
blazing tiger
cold parrot
#

neither will be easier

blazing tiger
#

I'm not sure about custom tooling though, I think unity editor handles serializable fields good enough

cold parrot
#

And you will do a bunch of work for spawning the views into that data.

blazing tiger
#

Couldn't I use scriptableobjects with a itemData field for this?

cold parrot
#

The question really is whether your view is much smaller than your world that’s held in the data to an extent that you actually need the separation for that reason alone

#

say you have a world with 100 planets but you only ever visit one at a time as a player (interactively), here it’s very impractical to not fully separate view and model

blazing tiger
#

I would, average case scenario, need to save up to 1000 entities per player

#

Not to mention the inventory

#

From developer perspective it would be easier not to separate anything

#

But I get what you're saying. I'm gonna reflect on my design a couple more times and try to determine whether I really need the separation

cold parrot
blazing tiger
cold parrot
blazing tiger
#

I've seen a talk made by the developer of Caves of Qud who uses a very similar system — he sends events, such as "get name" addressed to an entity, and the components attached to that entity intercept and modify said even

#

So "fluid container" intercepts the "get name" event and appends its current contents and amount to payload

#

Seems very clunky to me, but definitely solves the problem

cunning aspen
#

i am trying the change the rotation on one axis of my first person player when a key is pressed. i change transform.rotation using quaternion.euler(transform.eulerAngles.x, transform.eulerAngles.y, 30f) and changing back the z axis to 0 after a few seconds have passed from the time the key was pressed. it is working as expected but after that when using my mouse to look around the rotation changes for all axes

rigid island
cold parrot
# blazing tiger I think it's my time spent in web dev. You learn about importance of model and v...

I think in gamedev the reasons for separating modules/concerns are much more integrated, there is way less abstraction and entirely different abstractions here boost productivity for different reasons. and web’s obsession with MVC does not translate well if applied dogmatically or converted with web concerns in mind, the workflow in games, performance and reasons for change is very different. Only on a theoretical level they do align. But that is usually not helpful. Also depends on the type of game and its scale.

cunning aspen
rigid island
cunning aspen
#
{
    if (State == MovementState.Sliding)
    {
        slideTime -= Time.deltaTime;
        if (slideTime > 0)
        {
            player.localRotation = Quaternion.Euler(player.eulerAngles.x, player.eulerAngles.y, 30f);
            controller.Move(transform.forward * slideSpeed * Time.deltaTime);
        }
        else
        {
            player.localRotation = Quaternion.Euler(player.eulerAngles.x, player.eulerAngles.y, 0f);
            State = MovementState.Running;
        }
    }
}```
cunning aspen
dusk apex
#

The euler angle property is an interpretation of your rotation (quaternion). Expect the value to differ on calls to the euler angle property.

fair osprey
#

is there an easy solution for storing pairs of values that are unique and order agnostic? e.g. the pair (1, 2) will be treated the same as the pair (2, 1)?

#

(in c#)

cunning aspen
dusk apex
#

If the values differ but orientation is correct then the euler angle property is simply returning a different interpretation of the quaternion. If the orientation is incorrect and not just the values, then you've got something else modifying your rotation.

cunning aspen
dusk apex
rigid island
fair osprey
#

how would I go about that first part?

dusk apex
cunning aspen
#

screenshot of before sliding (note : x and z rotation values are 0 and the orientation is okay.
screenshot of after sliding (note : all rotation values are non zero and orientation is weird as well
unable to take screenshot of sliding

cunning aspen
# dusk apex We would need to see the mouse look script if it's related to that

    
{
    public float mouseSensitivity = 100f;
    public Transform playerBody;
    float xRotation = 0f;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

        playerBody.Rotate(Vector3.up * mouseX);
    }
}```
dusk apex
rigid island
dusk apex
cunning aspen
rigid island
dusk apex
cunning aspen
rigid island
#

mouse is already frame-rate independent, you should not use deltaTime

dusk apex
#

Mouse with get axis already counts as a delta

cunning aspen
dusk apex
#

That was a tangent though. Don't recall if inspector values are with local rotation or world rotation.

fair osprey
cunning aspen
dusk apex
dusk apex
dusk apex
cunning aspen
dusk apex
cunning aspen
dusk apex
#

Dunno, I'm not on my workstation right now. Try debugging the euler angle values and local euler angle values to see what your working with

#

The inspector values likely aren't what you think they are - do not rely on these values.

#

Local and non local most definitely should not behave the same if there's a parent involved

cunning aspen
#

alright, thank you for your help, i'll try figuring it out

unkempt swallow
#

in what way could a disabled script component still be affecting things? i thought disabling it would stop any and all code executions? but somehow it still has an effect on certain things i cant go into detail of

#

if a diff function calls a function from that disabled script directly, would it go through ?

unkempt swallow
#

or event

#

ohhhhhhhhhhhh no :(

knotty sun
#

absolutely, many things run on a disabled script

gray mural
unkempt swallow
#

rip

gray mural
#

The events are not invoked by the disabled class. You can invoke events from this class in other classes though

gray mural
unkempt swallow
#

networking

#

but the info i got is enough to figure it out, thanks o/ idk why i thought disabling it is enough

broken flume
#

Does anyone know if its possible to view the code of mobile games?

#

For Android

rigid island
reef garnet
#

Hi everyone, we're working on a crowd system for physically interactable crowds, like ragdolls, for a driving game and we've got a, janky first solution involving navmesh agents and rigidbody enabling and disabling. I want to know if any of you could link to articles, videos or even your own experience with simulating crowds and how to do it performantly

fair osprey
#

not sure if this is the right place to ask but I couldnt find a channel specifically for materials so here goes - is it possible to set a material colour to a gradient between two colours in c# code or do I have to create/assign a new material for that purpose?

merry stream
#

can someone help me think through the structure of my stats class? https://paste.ofcode.org/8Tg6Jv2DDcRHeNRhZMBPGE. https://paste.ofcode.org/QB3UyvUk4iSa94ZkyiubPW My game is similar to Path of Exile or Diablo with many stat "increases", "multipliers," etc. Right now it's kind of a mess but it SOMEWHAT works. However, i believe there is a much simpler way to achieve all of this. The main problems im running into are decreasing by a flat amount (ie taking damage) hence why i have a "RawCurrent" aswell as starting with some amount in the case of enemy presets (RawMax). It wouldn't make sense to reduce this amount in "Add" since it would be affected by the multipliers. Another issue is when a player levels up or changes gear while their stats are altered. How could I structure it in a way that preserves current stats (lowered health, mana, debuffs, etc) while easily changing their max stats. thanks!

merry stream
#

also, i feel there is a fundamental difference between stats like Health, Mana, Movement Speed since they are based on a "max" amount, while others are just a stat number, say "physical damage." how would I reconcile this?

indigo tree
feral knoll
#

Where would I request help for a Unity script issue?

velvet pebble
#

...which we're in I just realized

indigo tree
merry stream
feral knoll
#

I might post it here as well…

#

[HELP WANTED]
Hello, guys! I was wondering if I could get some help with a script. One of my team's coders (now on hiatus) recently converted some functions in our game's AssetFinder script to return an async Task<GameObject>. However, all the other functions that he hasn't touched are expected to recieve a standard GameObject. I'm not sure how to convert it to a normal GameObject, and I would appreciate some assistance, as I've never worked with Addressables or ASync.

NEW FUNCTION EXAMPLE:

    {
        string[] guids = AssetDatabase.FindAssets("t:Prefab");

        foreach (var guid in guids)
        {
            var path = AssetDatabase.GUIDToAssetPath(guid);
            var operation = Addressables.InstantiateAsync(path);
            GameObject go = await operation.Task;

            if (go != null && go.name.Equals(prefabName))
            {
                Collectable goCollectable = go.GetComponent<Collectable>();
                goCollectable.type = goCollectable.itemSO.type;
                goCollectable.icon = goCollectable.itemSO.icon;
                return go;
            }

            // Clean up if the prefab doesn't match
            Addressables.ReleaseInstance(go);
        }
        return null;
    }```
I need to take the result and turn it to a standard GameObject
tawny elkBOT
pure ore
#

For a dialogue system, should I opt for using constants? i.e static strings bundled in classes by character?

DAVE {
  publc static string Line1 = "Hello, I am Dave",
},
JOHNNY {
  public static string Johnny01 = "Hello, I am Johnny",
},
``` etc
cold parrot
rigid island
feral knoll
# rigid island !code

What do you mean? Are you asking to display the function in a code window? I'm not sure how to do that

rigid island
rigid island
#

anway, using constants like that would probably the most cumbersome method lol

#

not flexible / modular at all. Not an option when you want good code

feral knoll
rigid island
feral knoll
rigid island
feral knoll
#

the developer should be back in a week or two to handle this stuff moving forward, but progress has slowed to a halt right now and I really just want to fix this script so we can move on with further development

rigid island
feral knoll
#

In addition, I have other functions in the script that act very similarly but search for other assets like Tiles

mossy snow
rigid island
feral knoll
#

Hm...here's the original function. If anybody can help me rework it so that it can be used in builds, I would appreciate it immensely:

        string[] guids = AssetDatabase.FindAssets("t:Prefab");

        foreach (var guid in guids) {
            var path = AssetDatabase.GUIDToAssetPath(guid);
            GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            if (go.name.Equals(prefabName)) {
                Collectable goCollectable = go.GetComponent<Collectable>();
                goCollectable.type = goCollectable.itemSO.type;
                goCollectable.icon = goCollectable.itemSO.icon;
                return go;
            }
        }
        return null;
    }```
rigid island
#

well you can't use AssetDatabase for starters

#

its a UnityEditor class rather than UnityEngine (build)

feral knoll
#

yeah, I get that...the other developer suggested Addressables as an alternative, but now that also seems to be unviable, so I'm unfortunately at a loss

rigid island
#

Still unclear what your end goal for all this is

#

You could probably even use Scriptable objects to hold groups of prefabs etc

mossy snow
#

this whole thing seems like the end-stage result of a terrible plan to begin with. Why are you searching by name? The easiest solution is a SO, slap a serialized list of prefabs + names on it, #ifdef an editor context method that populates that list using AssetDatabase, and boom you have a runtime thing you can search much more efficiently than literally loading every single prefab you find to see if it's the right one

#

but since you're using string names, it's going to be brittle and awful to work with

rigid island
#

addressables pair better if you plan on using bundles or files stored else where, something like that

#

loading downloadable content, or large environments that need to be loaded into memory much later

feral knoll
# mossy snow this whole thing seems like the end-stage result of a terrible plan to begin wit...

so let's say I have a script for the player character that says whenever I use this item (let's say an empty bucket) while facing a body of water, the bucket gets removed from the inventory and a new item (the filled water bucket prefab) gets added in its place. I could add a direct reference in the script to that prefab, but then I'd need to create a new reference every time I make a new prefab that needs to be used in the script. whereas if I can just create a function to grab the preset by searching with a string parameter, I can grab the prefab by calling a function in the player script, no direct reference required. that's my goal with this function, and the others in the AssetFinder script

#

I'll happily admit that I'm not the most experienced Unity developer, but your proposed solution seems to involve a list of prefabs + names that I will need to update every time I save a new prefab for use in other scripts. I'd rather avoid that if possible, and be able to reference any prefab as needed without making references or leaving the script editor

mossy snow
#

no, you don't manually change the names or add to the list. You automate it so the editor does it for you

fossil blaze
#

How to prohibit the use of the StartCarryHold() method

feral knoll
fossil blaze
#

when you're holding an object?

feral knoll
lean sail
# feral knoll [HELP WANTED] btw, if anybody else is reading this chain of messages and can hel...

people arent gonna dm or just randomly work on a solution for you. try and implement it, and ask specific questions when you're stuck on something. I read some of the messages above, and some things dont really make sense.

Some of my prefabs do have SOs attatched to them,
SO's dont get attached to a prefab, they arent components. you would be referencing it through a script which is a component. You shouldnt need to "scan for them" no matter what you're doing

feral knoll
# lean sail people arent gonna dm or just randomly work on a solution for you. try and imple...

my issue with trying to implement it is that I really don't know where to start. when mentioning SO's being attatched to the prefabs, I did mean as a component. Sorry if that didn't come across clearly. But if you're saying I don't need to 'scan for them', then what was xEvilReeperx referring to with the serailized list of prefabs + names that automatically populates the list using AssetDatabse?

#

@lean sail I'm already stuck. If that means that I should be writing this thread in #💻┃code-beginner, then fine. But I haven't been able to find a solution for revising this function on my own, and when I'm being given solutions from others that I don't fully understand and therefore don't implement, what else can I do besides ask for more involved assistance?

lean sail
feral knoll
lean sail
#

the whole purpose of this is to populate your data at editor time. The code isnt in the build if you wrap it in the #if UNITY_EDITOR conditional

#

which is what they meant by "#ifdef an editor context method that populates that list using AssetDatabase"

feral knoll
lean sail
feral knoll
#

Gotcha

mossy snow
#

updated script, accidentally ifdef'd GetInstance :(

#

but I maintain this is a terrible plan, from your earlier description the player script knows too much and it's forcing you down this dark path

fossil blaze
#

help guys

feral knoll
#

I’ll try implementing it and let you know how it goes, though. And thanks for your assistance regardless

feral knoll
steady moat
# merry stream also, i feel there is a fundamental difference between stats like Health, Mana, ...

It really is a mess.

However, I believe saying that Health, Mana and Movement Speed are fundamentally different because they have a "max" is wrong. Other statistic could potentially have a maximum value as well.

Your main problem (decreasing, increasing) is an other things that could be considered fundamentally different per stats. However, I believe there is nothing wrong with how you did it. The only thing I would do is try to rename current and rawCurrent for something else. (base/baseValue could be a good choice)

Whenever you level up or your equipment change, you could have a refresh happens.

  • Drop all modifier from your stats.
  • Ask every provider of modifier to recreate their modifier.
  • (Do not reevaluate your current till all provider have not finish adding their modifiers)

As a side note, I believe Diablo use "bucket" for multiplier. You could have something similar instead of doing CurrentModifier.Increase and CurrentModifier.More.

fossil blaze
feral knoll
fossil blaze
short quiver
#

How to prohibit the use of the

lilac lance
#

Im making a game involving space orbits. I have a pretty simple setup where I divide objects into attractors and attractees. The player is to control one of the attractee objects. I want to later allow for the player to add forces to control the object, but for now Im trying to figure out how to calculate the future posistion of the object, for a line renderer to trace it.

I originally thought about using the Physics simulate, but that would move everything into X steps into the future, which I do not want. So I am guessing that I have to create a copy of all of the gravity objects then use physics simulate, or is there some better way that I overlooked

steady moat
feral knoll
#

[HELP WANTED, RESOLVED]
Currently trying to call a function that has no type arguments, but although no errors appear within the code editor, Unity won't compile the script because "The type arguments for method ' PrefabCollection.FindPrefabMyName<T>(string) ‘ cannot be inferred from the usage. Try specifying the type arguments explicitly, despite the function having been edited to not have <T> as an argument

        var instance = GetInstance();

        var entry = Array.Find(instance.prefabs, e => e.name == name);

        if (entry.prefab == null) {
            throw new InvalidOperationException($"Prefab with name {name} not found");
        }

        var item = entry.prefab;

        return item;
    }```
```inventory.AddItem(PrefabCollection.FindPrefabByName("WoodBucket(Water)").GetComponent<Collectable>());
native flower
#

So my unity is crashing due to the post-processing script plugin. I've found the line that is crashing and it's crashing because of a texture it's trying to read. i want to find the texture but i cant attach VS because unity is crashing when i open the scene that references the texture.
How would i attach VS to be able to debug scripts like post process which run in the editor?

mossy snow
#

I wrote that method using generics because:

  1. almost always, a serialized reference of a prefab that is a GameObject is a code smell
  2. your line, as written, can potentially add null items to inventory unless AddItem guards against it
feral knoll
mossy snow
#

your error implies FindPrefabMyName<T> (misspelled intentionally?) exists in the PrefabCollection script

feral knoll
#

The weird thing is that there isn't. I changed the name of the original function to FindPrefabComponentByName<T> in case I needed it. The version I sent in the earlier message is the only one currently in the script, which is why I'm confused that it's asking for generics

mossy snow
#

are you sure you're looking at the right line/script? Maybe you are trying to call it from elsewhere

feral knoll
#

Even if I delete the FindPrefabComponentByName<T> function, Unity still won't recompile the script and the error still persists

mossy snow
#

post the updated scripts + the exact error. I assume you aren't using any relevant third-party tools like hot reload that seem to throw a wrench into things occasionally

mossy snow
#

use code sites for anything larger than a snippet

feral knoll
#

lemme do that

#

writing the error now

#

Assets/Scripts/PlayerHandler.cs(90,48): error CS0411: The type arguments for method 'PrefabCollection.FindPrefabByName<T>(string)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

#

(CHECK LINE 90)

mossy snow
#

looks fine to me. Try these steps next, in order, to see if any solve the problem:

  1. restart Unity
  2. close Unity, delete Library/ScriptAssemblies folder, open Unity again
  3. Unity prefs -> External Tools -> Regenerate project files; restart Unity
  4. wipe Library entirely
quartz folio
#

Oh wait, you're using a different thing...

#

where is the generic version?

#

You removed the generic version, so presumably you never saved that change

#

Sorry, I didn't read the whole convo and did the bad thing. I've never seen this happen unless there are other errors or there hasn't been a save

mossy snow
#

the not-saved script is an excellent point though, my ide saves automatically so I didn't consider it. It could be that simple

quartz folio
#

some IDEs don't save all dirty files, which sounds very inconvenient

feral knoll
fervent coyote
#

Is there a way to get the playmode resolution? Screen.width doesn't seem to work with it...

fervent coyote
#

I'm having an issue with the screenshots being cut off while in the editor

{
    string _screenshotDirectory = Application.persistentDataPath + AstroEngine_ScreenshotDirectory;
    if (!Directory.Exists(_screenshotDirectory))
    {
        AstroEngine_WriteToConsole($"Directory '{_screenshotDirectory}' does not exist. Created folder");
        Directory.CreateDirectory(_screenshotDirectory);
    }
    string time = System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Year.ToString();
    Texture2D _screenshot = ScreenCapture.CaptureScreenshotAsTexture();
    //Save the file
    string _fileName = $"Screenshot {time}.png";
    File.WriteAllBytes($"{_screenshotDirectory}/{_fileName}", _screenshot.EncodeToPNG());
    audio.Audio_CreateUISFX("uiclick");
    AstroEngine_WriteToConsole($"Screenshot taken and saved to {_screenshotDirectory}/{_fileName}");
    //Prevent from garbage collecting
    Destroy(_screenshot);
}```

Here's the code I'm using for capturing the screenshot
severe sonnet
#

Is it possible to do transparent WEBM captures on the Unity Video recorder?

#

This sounds like a stupid question since it exports in VP8, but I've tried everything imaginable to find out how to make that happen and I feel like I've hit a wall

rigid island
#

ah it pays off to read the docs you see..

#

To get a reliable output from this method you must make sure it is called once the frame rendering has ended, and not during the rendering process. A simple way of ensuring this is to call it from a coroutine that yields on WaitForEndOfFrame. If you call this method during the rendering process you will get unpredictable and undefined results.

fervent coyote
#

Ohhhhh ok

upper pilot
#

Is there a way to save a List/Dict with JsonUtility?
I can use a struct, but I'd need a List/array to make it more useful.

#

or do I use the other Json parser, forgot its name

upper pilot
#

It seems like I cant save List of structs, but I will try again

knotty sun
upper pilot
#

oh no 😄

knotty sun
#

can't serialize something which is not marked as Serializable

upper pilot
#

Do I need to serialize all public fields too? It seems like that might be required

knotty sun
#

no, public fields are serializable by default as long as they are primitive types

upper pilot
#

float and enum

#

they don't seem to parse, trying with serializeField next

knotty sun
#

they are primitive types

upper pilot
#

It saves {}

knotty sun
#

then you are doing something wrong

upper pilot
#

I am saving:

List<AudioChannelVolume>

    [Serializable]
    public struct AudioChannelVolume
    {
        [SerializeField] public AudioChannel Channel;
        [SerializeField] public float Volume;
    }
#
string channelVolumeSaveData = JsonUtility.ToJson(AudioData.GetChannelVolumeList());
knotty sun
#

is AudioChannel also Serializable

upper pilot
#

but wouldnt it at least save Volume?(it's not serializable tho, let me add that)

knotty sun
#

no idea based on that code. Debug it

upper pilot
#

Debugging all the time

knotty sun
#

if you want a List you need that to be inside an object

upper pilot
#

oh thats what I thought might be the case, let me give that a go

#

Actually thats not very convenient, can it save dictionaries if they are inside a struct?

knotty sun
#

no

upper pilot
#

I suppose that I need an extra layer then to store a list only

knotty sun
#

yep

upper pilot
#

That works, thanks 😄

knotty sun
# upper pilot That works, thanks 😄

if you have a Dictionary to serialize you can break that down to a List of Keys and a List of Values before serialization and then reconstruct the Dictionary from the 2 Lists after deserialization

upper pilot
#

That sounds like a better solution too, this way I don't need 2 structs.

random nexus
#

Hi is there a way to wait until a gameobject has done being enabled?

mellow sigil
#

The object is enabled right after setting it enabled. What exactly do you want to wait?

knotty sun
random nexus
mellow sigil
#

Do you have some problem with it that you're trying to solve?

random nexus
#

im trying to wait for level to be enabled so i can spawn my character thats it

mellow sigil
#

You don't need to wait. SetActive is instant.

#

If it doesn't work then the problem is somewhere else

bronze mango
random nexus
#

so even if i have a really big scene is it still instant?

mellow sigil
#

You asked about enabling gameobjects. Are you actually loading a new scene?

random nexus
mellow sigil
#

So what does having a big scene have to do with it then?

random nexus
#

by big scene i mean enabling a large gameobject like a Level Gameobject

mellow sigil
#

It doesn't matter how big the object is or how long it takes to enable it. It's enabled on the next line after calling SetActive

random nexus
#

ok i get it but some times the characters falls even if i spawn it after i enabled the level

mellow sigil
#

That's an unrelated issue

primal wind
#

My brain just stopped working so, how would I get the delta of a vector using the previous and current value? It should be simple but my brain can't right now for some reason

gloomy briar
primal wind
#

Thanks

gloomy briar
#

alternatively, if you're really dealing with vectors as opposed to points, maybe you want the angle between them, which you can find using the cross product

thin aurora
#

If something can't be serialized it should be ignored, or at least throw an exception

#

But JsonUtility is a very bad tool for serializing JSON. Consider switching to Newtonsoft which will work properly. JSonUtility lacks a lot of basic features

#

Note that it does require you to use properties rather than fields. This is very normal and only Unity uses fields because it has very bad standards

dawn nebula
#

Is there any way to control the softness of shadows?

#

Like obviously there is hard vs soft. I'm saying the amount of softness.

hexed pecan
#

What render pipeline?

marsh marsh
#

Anyone worked with BehaviorGraph in Unity 6? I'm getting NullReferenceExceptions on my BlackboardVariables in my Action scripts and I'm not really seeing docs about it yet.

stable osprey
dawn nebula
dawn nebula
stable osprey
#

Built-in

marsh marsh
#

@stable osprey they're just nullreferenceexceptions when trying to set the values

#

or read the values

dawn nebula
stable osprey
#

but it's very probable you just didn't assign any values in the inspector

marsh marsh
#

oh, sec

stable osprey
#

for example you read myText.text but myText isn't assigned

marsh marsh
#

@stable osprey this issue is specific to the behavior graph. these variables are created in the behavior graph itself. i didn't even think they could be null because of that, since they're assigned a value in the blackboard itself

stable osprey
#

Imma ask for that screenshot after all.. full screen preferably 😛

#

click on the blue thing here:

marsh marsh
stable osprey
#

well, seems your SwimSpeedMultiplier is null at that time 😛

marsh marsh
#

yes, it is. i'm trying to find out why 🙂 i'm not seeing documentation for getting the values for that variable from the blackboard

stable osprey
#

did you check out the stuff in here?

marsh marsh
#

not particularly useful for this

stable osprey
#

ah, should you be calling base.OnStart() in the beginning of the method?

#

not sure where the initialization of the variables from the BehaviorAgent to the graph/script happens, sorry.

marsh marsh
#

nah, adding that didn't help

#

it seems like the blackboard variables are supposed to sync between the script and the graph as long as they're named the same. at least, i can't find any documentation saying otherwise

stable osprey
#

can u post the relevant parts of the script?

#

u can use ctrl+M+O to collapse it so I can only see the definitions if u want

#

(in screenshot is fine -- post as much as fits from the start)

marsh marsh
stable osprey
#

ah yeah no wonder they don't sync 😄

#

they should be [SerializeAsReference]

#

also, maybe blackboard variables need to be public, I'm not sure.. that's what the tutorial says

marsh marsh
stable osprey
#

they also add the [Serializable] and [GeneratePropertyBag] attributes to the class

stable osprey
marsh marsh
#

where are you seeing this in the docs?

stable osprey
#

I don't, first result for BehaviorGraph returns this video: https://www.youtube.com/watch?v=QpIBFLvumEc

The New Behavior package comes with some much needed functionality for building node based systems in Unity. Learn how you can take advantage of this new package to create custom node based logical flows, broadcast events, and build custom actions with a system that is extensible, serializable and easy to use.

NOTE: Requires Unity version of ...

▶ Play video
marsh marsh
#

alright, great news! different error now! wooo! thank you so much.

stable osprey
#

np 🙂

solemn ember
#

sup gang

#

I was trying to follow this

stable osprey
solemn ember
#

I have this

stable osprey
#

thanks

rigid island
# solemn ember

can you like post the code properly and with a coherent question attached to it ?

solemn ember
#

let me cook

stable osprey
solemn ember
#

when I try to drag them

#

they go to the center, and I can't move them at all

stable osprey
#

ya don't bother 😛 the issue comes from what I posted above

solemn ember
#
public static Vector3 GetMousePosition()
{
    Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    return mouseWorldPosition;
}```
#

nah, it's fixed, I think

#
void OnMouseDrag()
{
    _rb.isKinematic = true;

    Vector3 objPosition = ExtensionMethods.GetMousePosition();
    objPosition.y = 1.5f;

    transform.position = objPosition;
}

void OnMouseUp()
{
    _rb.isKinematic = false;
}```
#

I mean the code is fixed, but it still does that

rigid island
stable osprey
#

it's still not 100% proper if you're using a UI canvas

solemn ember
#

I do have a Canvas, but the cards are 3d objects

stable osprey
#

LOL yeah that's an issue xD

rigid island
#

your camera is prospective and you're dealing with the Z on nearclip issue

stable osprey
#

this ain't gonna work

solemn ember
#

oh... any... tip?

rigid island
#

did you read the link provided to you

#

or you can try to 0 out the Z

stable osprey
#

and.. why are you using 3D objects on a UI? 😛

solemn ember
solemn ember
solemn ember
rigid island
#

much easier to use Plane usually

#

but can also try

var pos = Camera.main.ScreenToWorldPoint(etc..
pos.z = 0; // or whatever position 
mything.position = pos```
solemn ember
#

let me try that

solemn ember
#

didn't work, let's see xD

solemn ember
#

didn't work XD

solemn ember
#

people will be able to move the camera

#

I would like something that works from any angle

#

would using a plane like you're saying work for this?

rigid island
#

like its invisble but the ray can capture it so you can have movement always be proper

solemn ember
#

ohhh

#

super good method

#

right now is kinda messy but

#

I have a box collider on my invisible table, would that work?

marsh marsh
stable osprey
#

thanks for the update

stable osprey
rigid island
rigid island
#

why are there rigidbodies on the card lol

stable osprey
#
void OnMouseDrag()
{
    _rb.isKinematic = true;

    var mousePos = Input.mousePosition;
    mousePos.z = 0;
    Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePos);
    objPosition.y = 1.5f;

    transform.position = objPosition;
}
#

@solemn ember

rigid island
#

Input.mousePosition is vector2

rigid island
#

already has a 0 as z

stable osprey
#

cards have physics duh high

solemn ember
rigid island
solemn ember
#

it's like a tabletop simulator kinda project, something to pullup quickly so we can show the game to people

stable osprey
rigid island
# stable osprey

its vector3 to not cause issues with calculations n having to cast v3 n v2 but its technically only a vector2 captures

#

its pixel position of your mouse

stable osprey
#

if u insist this might even remotely be correct in ANY use case I suggest you re-read this xD

stable osprey
rigid island
stable osprey
#

however just go with the raycast mode imo

rigid island
#

agree. ScreenToRay much easier

#

esp if dealing with colliders

#

but might still need plane to capture the dragging movement of a card

solemn ember
#

ahm

stable osprey
#

yeah, on the link one of these would be the most appropriate way to correctly identify the target world position.

solemn ember
#

okay so screentoray

#

the rigidbodies, I want to give freedom of movement to people and also make it feel like if it was playing in real life

#

or aiming to that

rigid island
#

imo a plane makes more sense

solemn ember
#

ya'll fighting for me, that's cute

rigid island
#

not at all lmao

solemn ember
#

whoever wins I'll give a kiss in the cheek

stable osprey
#

I want riches and fame instead

rigid island
#

I'm debating myself if one is better than other cause I used both, in similiar situation

rigid island
stable osprey
#

tbh I always reach some hacky fixed-or-fake-distance + cast downwards to get the actual world position when I wanna use that in 3D

#

mostly need ScreenToWorld for 2D

solemn ember
#

so, raycast to the plane?

rigid island
#

try both see which one fits your needs

stable osprey
#

that'll be best for your card game yeah

rigid island
#

you need to learn to experiment and trial n error

stable osprey
#

the alternative is actual-physics-based, so you find the ground and offset upwards by some amount

#

but this might end up dragging the card on the floor on your specific case

solemn ember
#

nice

#

this works

#
void OnMouseDrag()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out RaycastHit hit))
    {
        _rb.isKinematic = true;
        Vector3 cardPos = hit.point;
        cardPos.y = 1.5f;
        transform.position = cardPos;
    }
}

void OnMouseUp()
{
    _rb.isKinematic = false;
}```
#

thx gang

vast patrol
#

so i still dont know whats better to use class or struct

knotty sun
vast patrol
#

few arrays with data of another type

leaden ice
#

depends on what you're doing with the data

vast patrol
#

that store very much infi

knotty sun
#

if the object contains other objects then, generally, class is better

#

but object lifetime is also very important, shorter lived objects are better as structs

vast patrol
#

short lived but intense operation

#

so struct is for primitives

knotty sun
#

basically yes

vast patrol
#

what about very large arrays of something like floats

knotty sun
#

arrays are objects

fair osprey
#

so I created a Shader that takes two colours and puts them on a material as a gradient

#

works like a charm

#

but I dont know how to access the colour properties in code

#

this is how the shader looks in editor

#

this is the code Ive been trying, which doesnt seem right in the first place but Im not sure what other options Id need to use

knotty sun
fair osprey
#

well the issue is on the coding side

#

in c#

#

not the shader

simple egret
#

Using shader graph?

fair osprey
#

aye

simple egret
#

The names of the parameters you set in the graph are only for display, you need to look at the Reference Name of a parameter. It's the one you use from the code

#

You can rename them as well

fair osprey
#

oh my god

#

thank you

simple egret
#

np

knotty sun
fair osprey
#

works flawlessly now

#

I was just one _ away from the correct answer lmao

eternal dome
#

well well well

low rapids
#

Any good Tutorials that are simple and explain the thematic of changing variables in another script from a diffrent script? I just cant figure it out

fair osprey
fair osprey
#

got it, ty

rigid island
#

not a code question

serene needle
#

Where should i ask about this?

rigid island
serene needle
#

Ok my bad

rigid island
#

all good

vapid apex
#

hi. my inventory system has an item class, where each item basically just contains a string identifier.
when rendering my inventory i basically want to look up the icons based on the identifier.
what's the best way to do that? is there any built-in data-table or so that i could use?

wintry crescent
vapid apex
#

i dont want my items to contain any references, i want them to be simple structures basically

wintry crescent
# vapid apex i dont want my items to contain any references, i want them to be simple structu...

with ScriptableObjects you can define the items with their names and sprites and identifiers and anything else you may possibly need that is related to said item
and then you can make a Dictionary at runtime that stores the identifiers as keys and scriptableobjects as values
and keep the identifiers inside your inventory class
and look up the ScriptableObjects from that Dictionary using those identifiers and pull things like icons from that ScriptableObject

#

also consider switching to int IDs rather than string ones

#

string IDs are p a i n

#

and they WILL screw you over

vapid apex
#

i appreciate your help, but i already know about scriptable objects. i'd rather bring back my original question: is there anything built-in or in a package that lets me link assets with identifiers in a table?

#

addressables maybe? and making a specific category?

mossy snow
#

that would be taking a bad idea and then implementing it in the most convoluted possible way

#

if you need a table to look up identifiers, implement it yourself in a few lines of code. Somebody asked a similar question yesterday about looking up prefabs by string identifier, so maybe you can have a look there to see if that might be adapted to your needs

wintry crescent
# vapid apex i appreciate your help, but i already know about scriptable objects. i'd rather ...

the way I've always done it, is create a key-value Dictionary where the key is the identifier and the value is something like scriptableObjects - and since you can't show dictionaries in the inspector, whatever you're using as values needs to have a reference to the key as well

If you're determined to have another way, you can use the Resources.Load or Addressables to load your data, and have a function that converts the string identifier into a path to load the addressable

#

but you're gonna have to keep that in mind while creating and assigning your addressables and honestly it's not the way to go

#

if you do items, you do scriptable objects it's as simple as that I really don't know what to tell ya

#

it's the solution to the problem and unless you have quite a unique reason for why you can't use scriptable object, they're the way to go

vapid apex
#

ok, i might consider scriptableobjects. but i'd still be interested if there's data-tables like in unreal. so i guess there isnt?

wintry crescent
#

but you can't show them in the inspector easily

vapid apex
#

i remember doing a custom class once where you manually had to serialize the dictionary

#

into 2 lists (key list, value list)

wintry crescent
#

because if you want to change something or remove an item it's in 2 places and it's difficult to match them up in editor etc etc

vapid apex
#

no, the class used a dictionary, as i said on serialize you had to serialize it as 2 lists

#

and on deserialize fill the dictionary again

wintry crescent
#

and you end up maybe creating a struct to keep the key/value list in one place and create a dictionary out of that and maybe there's an easier way to manage them than a shitty list within an object within an inspector window and oops you're at scriptable objects

wintry crescent
#

but how do you serialise deserialise those lists into a dictionary? you go by order?

#

that's my point

vapid apex
#

so i guess if i use scriptableobjects i'll still need some sort of lookup table if i want to spawn an item by identifier and not by reference

wintry crescent
#

but why do you not want to use scriptable objects?

#

the scriptable objects approach is simply to create the lookup table without pulling your hair out

vapid apex
#

i dunno, something something "dont mix backend with frontend"

wintry crescent
vapid apex
#

i guess if i'd want to go the rimworld route, it'd also be nice if the identifiers are the actual classnames, so it's kinda data-oriented

#

which seems nice for modding

wintry crescent
#

keep identifiers as ints

#

use names

#

in the scriptable object

#

strings that have no actual bearing on anything except they're being displayed in your ui

#

don't rely on string for identifiers ideally ever or almost ever

vapid apex
#

i have to use identifiers anyways once i save something to json or xml

wintry crescent
vapid apex
#

i prefer when you can edit save-files though and read what they actually contain

wintry crescent
#

then at least implement some safeguards for your system that will make sure you're not looking for random spaces at the ends of items, or different capitalisations ruining your day ¯_(ツ)_/¯

vapid apex
#

also when modders add new items you can have namespaces for items

wintry crescent
#

modders don't even have to know about the ints

#

I'm saying that under the hood you should use ints instead of strings

#

otherwise you're gonna be hunting spaces at the ends of strings until you move on from this project

#

well, do as you will

#

scriptableobjects are the way

vapid apex
#

hm i cant really find much info about inheritance with scriptable objects. they all seem to use very very simple examples of inventory's and everything is supposed to be one Item and one ItemData class.
but what if i have StackableItemData inhering from ItemData?
then i need an Item class and a StackableItem class and the StackableItem needs a reference to the StackableItemData
so basically when i add an item to an inventory i need to know its class and its scriptable object reference

#

scriptable objects are only supposed to hold data right? e.g. they should hold maxAmount but not amount!?

#

since they are not instances, they are just one thing in memory holding static data

#

other option is having one big monolithic item and itemdata class i guess, but that kinda sucks

quaint rock
#

you could always have the asset ones define data and have in memory instances for stuff like current quanity

lean sail
vapid apex
#

i have Item, StackableItem and HealthPotionItem right now.
and they get their needed data from ItemData, StackableItemData (inherits ItemData, adds maxStacks) and HealthPotionData (inherits StackableItemData, adds healAmount)
so basically when i want to add a health potion to my inventory i need to call:

(property) HealthPotionItemData healthPotionItemData;
...
inventory.AddItem(new HealthPotionItem(healthPotionItemData));

if i want to add a basic item i need to add:

(property) ItemData ItemData;
...
inventory.AddItem(new Item(itemData));

having the data passed in the constructor so the items can store a local reference to the data object.

so i basically need a lookup table like:
[identifier, Item SubClass, Scriptable Object Reference]
if i want to spawn items

mossy snow
#

Why does inventory know details about items and item data? This seems like a design problem to me, and inventory is going to end up having to know about every type of item and every type of item data (whatever that is)

steady moat
# vapid apex i have Item, StackableItem and HealthPotionItem right now. and they get their ne...

You should not use inheritance for to add the concept of Stack.

The reason is that C# does not permit multiple inheritance and if you ever want to make something like a DurabilityItem or a EphemeralItem you would not be able to have a Stack + X behavior. Instead, you should use composition.

public class ItemData
{
  private List<ItemDataComponent> components;

  public bool TryGetComponent<T>(out T component) 
    where T : ItemDataComponent
    {...}
}

public class ItemDataComponentStack {...}
public class ItemDataComponentDurability {...}

mossy snow
#

that looks like a terrible design too, unless you intend to add those components at runtime for some reason

vast patrol
#

does trycatch cause any lag when no error found?

steady moat
maiden fractal
mossy snow
# steady moat What do you mean ? If the idea is to serialize the data, you either: - Use a Fa...

your design implies runtime addition of presumably immutable properties like whether something stacks. And if you think a little further into the future, what if one Item wants to interact with another Item? You'll have to put a string identifier on them to tell them apart and have no compile-time protections at all. Why wouldn't HealthPotion just be an ItemData that has Stackable + Durability fields? That would be the right way to do composition here

steady moat
# mossy snow your design implies runtime addition of presumably immutable properties like whe...
  • There is many way to distinguish between one item or an other. I usually use a Definition (ItemDefinition in this case)
  • If you think even further ahead, you are going to realize that you needs a way to interact with Stackable Item that are not HealthPotion. Your only alternative would be to use an interface (IStackable) which would means that you need to redefine all the code of a StackableItem. (You might have events (OnStackModified), maximum value or other behaviour that would be appropriate to be share through all items)
mossy snow
#

You have a ItemDefinition that defines the data that defines what an Item is? Why? And no, if I were designing this there wouldn't be stackable items. All items would be stackable. Some would just stack up to 1. Otherwise you end up with those corner cases that you're talking about, where actually Items don't all have the same interface and so can't be treated the same way

steady moat
#

Also, I'm not sure what is the issue that each item has different Interface.

mossy snow
#

your ItemDefinition as described is redundant if you also have an ItemData containing "component"s which is the real definition of what a item is. You could merge them

#

and no it doesn't bloat code; items only implement what they need. Make behaviors virtual with default implementations. You get the benefit of type safety this way, too

steady moat
steady moat
#

Also, the pattern you suggest would be Template Class Pattern which in it essence is not an Anti-Pattern however the way you are using it definitely makes it one.

#

That being said, as long as your item behavior are relatively small, you would not have any issue with the approach you suggest.

mossy snow
#

no it doesn't. Like I said, all items are designed with the same interface in mind. And you never modify Item, you derive from Item to implement new items and define their behavior

#

be careful slavishly following solid methods btw, those are intended for long-term business applications and can be harmful in game programming where it's mostly build it, you're done, move on with no long term support

steady moat
steady moat
lean sail
mossy snow
#

I don't modify Item ever, because it has all the common behaviors needed already. And all items need all behaviors. For example, in your design, how does the user merge stacks, one being a stackable thing and the other not? The correct, default behavior that all Items in my design share is that nothing stacks, and Items individually determine what happens (they can override this default-supplied behavior). No open/close violation there

steady moat
steady moat
mossy snow
#

Item is an interface that only defines inventory-related things. Does the behavior of a chest belong in an inventory?

steady moat
#

If the item needs to hold all the item a chest holds, yes it does.

mossy snow
#

you said behavior though. Chest would just be yet another inventory and do all the same things inventory does. Chest logic wouldn't go there

steady moat
#

I meant an item that is a chest (I.E. holds other item when in inventory)

#

You would by example, have the possibility to open the item to see what is inside.

mossy snow
#

lol I think we've really got into the weeds here. I don't think I would understand your design unless I could see it implemented in code. There's no reason you couldn't have an ItemContainer that contains an Inventory, and its Use or Inspect or whatever inventory-related behavior opens another ui that shows its contents

steady moat
#

So, you would use inheritance to add the behavior.

If you have a second behavior that also requires inheritance because the behavior cannot be shared, you would not be able to have both of them at the same times.

By example, if you were to say that a ChargingItem is required, you could not have a ChargingItem that is also a ContainerItem.

mossy snow
#

You're trying to come up with weird edge cases for some reason? Yes, if I needed behavior like that I'd factor out the common stuff and make ChargingContainerItem sure. If that's actually a common case and not a one-off, it starts to seem like maybe every Item is a ChargingItem that has one charge and then it's solved easily again

#

but I don't think I'll be able to convince you over your way so this conversation isn't productive and we should move to a thread since it's way past the original point

steady moat
#

Also, you should really consider the aberration that is ChargingContainerItem.

mossy snow
#

lol that was your weird edge case, not mine. And it's likely to have only a few dozen lines, given that common logic would be factored out so ContainerItem and ChargingItem presumably both exist and use it

steady moat
broken heron
#

Trying to figure out a better way to control my npcs turns in my game. Currently I have everyone in a list and it controls their turn with a bool.

It works fine but the more npcs I add the longer a longer the turn waiting gets. In many roguelikes for instance the npcs move dam near instantly. What techniques can I use? I thought about coroutines with a foreah loop but then npcs sometimes stack on each other.

lean sail
broken heron
#

Like the base class has a bool that when true they can move. Wouldn't just preforming their movement in update make them move nonstop? I could very well be doing this completely wrong.

lean sail
broken heron
#

I currently have it like so ```public class TurnManager : MonoBehaviour
{
public List<BaseMobile> characters = new List<BaseMobile>();
private int currentIndex = 0;

void Start()
{
    if (characters.Count == 0)
    {
        characters.AddRange(FindObjectsOfType<BaseMobile>());
    }

    if (characters.Count > 0)
    {
        StartTurn();
    }
    else
    {
        Debug.LogError("No characters found for the Turn Manager.");
    }
}

void StartTurn()
{
    BaseMobile currentCharacter = characters[currentIndex];
    currentCharacter.CanMove = true;
    Debug.Log($"It's {currentCharacter.gameObject.name}'s turn");
}

public void EndTurn()
{
    BaseMobile currentCharacter = characters[currentIndex];
    currentCharacter.CanMove = false;

    // Refresh tile for the current character
    currentCharacter.RefreshTile();

    currentIndex = (currentIndex + 1) % characters.Count;
    StartTurn();
}

}```

#

and it works, it's just it cycles through all the characters then the player moves. The more NPC's the longer it takes which is expected. But I know there are some games that have near instant NPC turns in turn based games. Was just curious of some insight if anyone had any that might work.

leaden ice
#

This code just manages the list

#

If you want it to go faster that'd be elsewhere

indigo tree
broken heron
#

that would be this then?

    {
        if (baseMobile != null && baseMobile.CanMove)
        {
            bool threatDetected = DetectThreats();
            if (!threatDetected && currentState == AIState.Flee)
            {
                SetNextState();
            }
            HandleState();

            // Rotate towards movement direction (optional)
            RotateTowardsMovementDirection();

            // After performing actions, end the turn
            EndMyTurn();
        }
    }```
lean sail
#

i assume its less about the processing logic taking awhile, but how this code or the movement code runs. Start calls StartTurn once. Nothing here calls EndTurn and nothing here would happen more than once without another script using Update or a coroutine.

indigo tree
broken heron
#

wouldn't it only move the npc if their bool can move is true no matter where it is?

#

I guess saying that outloud sounds bad

leaden ice
#

Needs to be sped up

broken heron
#

You are right

    public void ExecuteAI()
    {
        if (baseMobile != null && baseMobile.CanMove)
        {
            HandleState();
            RotateTowardsMovementDirection();
            EndMyTurn();
        }
    }

    public override void PerformAction()
    {
        if (aiCharacter != null)
        {
            aiCharacter.ExecuteAI();
        }
    }```

I've changed it to call PerformAction on the NPC turn.
indigo tree
#

That should speed it up. Ai will not be running idly anymore.

leaden ice
#

It's unclear to me how this ExecuteAI code works. Two of those function calls seem like an "every frame" thing, but EndMyTurn is happening each frame?

indigo drift
#

I'm reading the documentation for the StreamReader class rn, I want to try the method ReadBlock and it has the arguments char[] buffer, int index, int count, does anyone know what each of these arguments do for the method? I can't find any information on what exactly they're for

brazen spruce
#

Hey, I have a problem with the Unity particule system. I have an object pooling system for obstacles in my game, and I would like to have particles whenever the obstacle linked with it is disabled. The problem is that I need to particles to get the velocity of the obstacle that is getting disabled. I tried having the system as a child and using the current velocity in Inherit Velocity (I'm using physics for my velocity, not transform), but this doesn't work if I disable the parent. Any ideas of how I could do this ?

queen sky
#

How do I access OnValueChanged or every other thing in C#?

quartz folio
rain minnow
queen sky
#

As you pointed out I'm not using the right system

#

Honestly I'm not even sure what I am using right now and how to change it lol

quartz folio
#

You've probably just declared the wrong type

queen sky
#

Just basic GO functions I think

quartz folio
#

can you link to your !code

tawny elkBOT
quartz folio
#

(gdl.space is down)

queen sky
quartz folio
#

Compiles fine for me

#

Does it compile in Unity?

queen sky
#

Wait a second, you are completely right

#

It compiles in unity just fine

#

I'm so sorry lol 💀. It seems my IDE is confused

quartz folio
#

hit the Regenerate Project Files button in Edit/Preferences/External Tools

queen sky
#

Yep, it worked, thank you. 🙏

#

I also had to invalidate caches in my IDE (Rider)

twilit scaffold
#

Am i just not understanding how this works, or does checking for a Quest Condition every frame sound like a bad idea?

soft shard
twilit scaffold
# soft shard To me, anything that sounds like it should be an event, sounds like a "bad idea"...

Ok great, i fully agree. Hopefully i can get this Asset maker to update the system, as i am pretty locked into it. Unfortunately, as is expected, the system got big, and he has forgotten a bit of how it works. There are not proper triggers for that exact scenario you described within his system, without checking every frame (or every 'some set time'). perhaps both he and i are missing something, but seems it was just not considered properly. Thanks

soft shard
# twilit scaffold Ok great, i fully agree. Hopefully i can get this Asset maker to update the syst...

Np, I dont know how complex that assets system is, but maybe you/asset creator could look into adding a Broadcaster/global event system ontop of it, to replace the "every some set time" checks, that way objects, locations, npcs, etc that are relevant to quests can call a static function that triggers what "every some set time" would otherwise do, and neither the quest objects, nor the asset needs to know exactly who/what is triggering the events (so you wont need direct references)

twilit scaffold
lean sail
# twilit scaffold Ok great, i fully agree. Hopefully i can get this Asset maker to update the syst...

sometimes assets are just poorly made or the developer just isnt that experienced. id suggest to try make a workaround instead of waiting for them to do anything.
Im not really sure how they wouldve made such a system that even checks every frame. there should definitely be events to tie into and id question the quality of this asset heavily before continuing. This isnt something a proper developer would just miss

solemn ember
#

sup gang

#

I'm looking to make a player hand for my cards game

#

like this, but in 3D

#

do you have any good video source on how I could make that? I've been looking and can't find anything yet

twilit scaffold
# lean sail sometimes assets are just poorly made or the developer just isnt that experience...

agreed. I am attempting a workaround now, but my knowledge is limited. I think he thinks that there is a way to trigger it, but his code has changed so much since he first started making the Asset, that i believe there are issues he has not yet comprehended.. there is a bit of a language barrier too, so that is making it a little more difficult. I am going to keep digging to see if i can find another way, or if it is just that i do not understand something major about his system! (pretty sure it is not that, but i have to make sure)

twilit scaffold
lean sail
gloomy smelt
mellow sigil
#

That does detect multiple objects. They're in the hits array. What do you want to do with them?

gloomy smelt
#

but it still only return one object

#

oh wait

#

i think it's because of the if statement. how can i make it return all the object it hits?

#

private void FindTarget()
{
RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, TargetingRange, (Vector2)transform.position, 0f, enemyMask);

    if (hits.Length > 0)
    {
        target = hits[0].transform;
    }

}
#

how do i turn this into detecting all object it detects?

#

do i make for each statement?

cerulean heron
#

how many raycast hit u have?

#

since u only said hits[0].transform, which u only specified one hit

gloomy smelt
#

I want it to hit all the enemies within the circle. it acts like a radar

mellow sigil
#

target can only store one gameobject. Change it to private Transform[] target; and then set target = hits

#

you'll have to then change the entire code to take into account that target is now an array

celest vault
#

ideally call it targets :p

cerulean heron
#

then u need more than one raycast point from the ur position to hit all the points in enter the collision u making

#

which will be like spider legs shape

mellow sigil
#

It's a circlecast. No need for raycasts.

cerulean heron
#

oh i didn't see the circle cast one

#

ya u need to store an array not single object for targets

mellow sigil
#

Although I suspect it should be OverlapCircle instead

wraith elbow
#

Hi!
I was wondering if it's possible to reference an object stored in a ScriptableObject from another ScriptableObject?

Basically I want to have public class First : SciptableObject act as a sort of "database" for objects (public List<object>).
Then, I want to be able to have a public class Second : ScriptableObject that can reference any of the objects from the First using some sort of dropdown.

Currently I think I can solve this with a custom Editor that creates such a dropdown, but I was wondering if there was a better/more native way of doing that?
Also if it's safe to do in terms of serialisation? Can I reference objects in such way and save references instead of copies?

plucky inlet
plucky inlet
gloomy smelt
#

yea and im'm trying to figure out how to return all of the game objects it hit

plucky inlet
#

Either make a simple for loop or cast to List and use foreach

gloomy smelt
#

since it works like a radar, I plan on having all the game objects it detects to be submitted to another tower and hit it with projectiles

gloomy smelt
#

thanks tho

wraith elbow
celest vault
# gloomy smelt wouldnt be using for each easier?

i mean that entirely depends on what you want to use the hits for. you can't just foreach over all of them and assign each to target. that would mean you just assigned the last item in the array once control leaves the method.

plucky inlet
celest vault
#

why would you have to cast it to a list?

#

you can foreach over arrays

plucky inlet
celest vault
#

what?

#
foreach (var hit in hits) { }
gloomy smelt
#

wait

#

lemme find it

plucky inlet
celest vault
#

who even does that in 2024

#

but you do you

plucky inlet
celest vault
#

List<T>.ForEach specifically

plucky inlet
#

If I get a list of whatever callback, I for sure use foreach

gloomy smelt
celest vault
#

yeah, foreach, certainly. but pretty much never ForEach :p

plucky inlet
celest vault
#

in this case, maybe. but use receivelmages.ForEach(Debug.Log) here

#

no reason to write out the lambda

plucky inlet
gloomy smelt
celest vault
#

log writing is pretty much the only place i use ForEach as well

plucky inlet
celest vault
#

cause it's longer and unnecessary :p

#

and i'm not sure unity's compiler version is able to optimize it away as a static anonymous function

#

so just pass the method group

mellow sigil
plucky inlet
mellow sigil
#

That's what I said, yes

gloomy smelt
#

i mean this part?

        targets.Add(hit.transform);
mellow sigil
#
private void FindTargets()
{
    targets = Physics2D.CircleCastAll(transform.position, TargetingRange, Vector2.zero, 0f, enemyMask);
}

That is all you need

celest vault
#

they're getting the transforms of the hits though?

mellow sigil
#

It's better to access the transform later when needed

celest vault
#

i'd agree

potent sphinx
#

Crazy abstraction

quartz folio
#

I always wonder whether there's any cost incurred

solid relic
#
public void PlaySound(string fileName)
{
    Debug.Log(fileName);
    Debug.Log(GameManager.instance.clipDictionary[fileName]);
    audioSource.clip = GameManager.instance.clipDictionary[fileName];
    audioSource.Play();
}

The line where i set the audio clip is returning an error: Object reference not set to an instance of an object, this error is for GameManager.instance.clipDictionary[fileName] and the debugs show that it isn't null, so i'm unsure what the error is about

thin aurora
# solid relic ``` public void PlaySound(string fileName) { Debug.Log(fileName); Debug....

A null reference error is very easy to debug.

  1. Log the value of GameManager.instance
  2. Log the value of GameManager.instance.clipDictionary.
  3. Log the value of audioSource.
  4. Depending on the collection type, log the value of GameManager.instance.clipDictionary[fileName]. This is likely a Dictionary, in which case you don't have to do this as the exception would be different.
rigid island
thin aurora
#

When you found the invalid value, either prevent it with a null check, or ensure it has the value. We can't help you with this unless you share more information

solid relic
#

These are my debugs and my script to get my audio source

thin aurora
#

I am missing log messages

#

Optionally, you can do a comparison against null so it's more clear

rose egret
rigid island
thin aurora
#

GetComponent can also return null, FYI

#

So the screenshot does not matter

rigid island
#

yeah you never logged audioSource to make sure its not null

rose egret
rigid island
#

if the log is properly logging the element in collection, is most likely audiosource

solid relic
#

My unity is being slow right now, i'll let you know how the debugging goes in a bit

rigid island
#
public void PlaySound(string fileName)
{
    Debug.Log(fileName);
    AudioClip clip = GameManager.instance.clipDictionary[fileName];
    Debug.Log($"clip {clip} ready to play in {audioSource}");
    audioSource.clip = clip;
    audioSource.Play();
}```
solid relic
#

Alright so.. i debug.log(audioSource); in Start() and it doesn't come back in null.. but then in my method it does return null

#

Which makes 0 sense because i never set it to null

#

I'm making it public right now and then seeing if it goes to null

wraith elbow
#

Is anyone here familiar with the mechanics of [SerializeReference]?
I'm looking at the saved asset file and see these rids

 items:
  - rid: 1445398361900843011
  references:
    version: 2
    RefIds:
    - rid: 1445398361900843011
      type: {class: Modifier, ns: GAS, asm: Dreadpon.GAS}
      data:
        _level: 1
        _displayName: Stuff 1
        _labelName: Stuff 1 [LVL 1]

Is there a guarantee these will stay constant across editor relaunch, project exports and end user launches?
I want to reference these rids in a ScriptableObject as a "link", and retrieve data from it using ManagedReferenceUtility.GetManagedReference() both in Editor and at Runtime

solid relic
rigid island
solid relic
open plover
#

If you press the home button in mobile or respond to a notification, which one is called? OnApplicationFocus or OnApplicationPause

open plover
rigid island
# open plover Does not work on the simulator

anyway as described in docs

On Android, when the on-screen keyboard is enabled, it causes an OnApplicationFocus( false ) event. If you press Home when the keyboard is enabled, the OnApplicationPause() event is called instead of the OnApplicationFocus() event.

rigid island
open plover
trim schooner
#

OnApplicationFocus does work with the editor.

trim schooner
#

Pause probably does too, but I'm not sure I've used it to know for sure.

#

All you have to do to test Focus is to click on a different app in Windows, and then return to Unity

open plover
trim schooner
#

Yeah it does

#

Simulator is just a view anyway, it's the editor that's giving you the calls

open plover
#

It doesn’t at least for me

#

I have a debug.log in those methods to doublecheck

#

When I press play, both onapplicationpause and onapplicationfocus is called

#

Then never again no matter what I do

rigid island
#

I can't even test ios cause no iphone lul

#

i can test android device if you want tho

open plover
#

I mean I can send my friends the apk thats not the thing

trim schooner
#

But you don't need to be in simulator to test this.. just change to game view (or have both open)

rigid island
open plover
#

Yes I’m on my mac

#

Sadly I didn’t install xcode yet

rigid island
#

if you plan on release to iOS you need it at some point 😛

open plover
#

I’ll do it later when the internet is better

#

I mean the only reason I didn’t download xcode is because

#

It is harder to distribute my friends the game via whatsapp or whatever

rigid island
#

aint no way to do that anyway

open plover
#

I don’t even know if I can send the .ipa file and they could open it

trim schooner
#

It's much easier to just use TestFlight

open plover
rigid island
open plover
rigid island
#

unless you use cydia impactor or something similar

trim schooner
#

You can sideload ipa's

open plover
open plover
#

Yea I’m not at that part rn

#

I need to set up a po box

#

And many other things

open plover
trim schooner
#

You need a dev account to share anyway. You can't make a shareable IPA without a dev account, all you can do is build to a local device

open plover
trim schooner
#

Haven't had to do it in years, used to just be able to do it via iTunes.

rigid island
#

impactor isn't just for jailbroken, it would work sideloading IPA . but its gray area of legality
oh says on site, as of 2019 its broken and only works only using the dev license. RIP

open plover
#

You mean with itunes?

trim schooner
#

a local device... a device you have locally with you.. physically ...

#

We're wildly off topic for this chan now

open plover
open plover
rigid island
#

xcode lets you test on your local device but you can't distribute without Apple Dev license

trim schooner
open plover
faint tree
#

hmm does anyone know why my sprites vanish when i change their shader? only happens on some levels and not others

solid relic
#

Can i make a unity toolkit ui worldspace?

faint tree
#

thank you

trim schooner
prisma hatch
#

hello lads, I've encounted a problem and requires assistantance!

I'm trying to get the raycast of camera.forward to spawn an object at its' max raycast distance if it does not hit anything at all, is there a way to achieve this?

mellow sigil
#

yes

prisma hatch
#

thank you!

mellow sigil
#

Or, origin + direction * maxDistance is the "end point" of the ray

rigid island
#

yea much simpler ☝️

mellow sigil
#

assuming direction is normalized

prisma hatch
#

that's actually a cool work around

mellow sigil
#

It's not a workaround, that's how you do it

prisma hatch
#

oh right, my bad for the wording

rigid island
#

you are forgiven

prisma hatch
#

works like a charm, thanks fellas

#

have a great day

tawdry jasper
#

I have ui code updating some TextMeshProUGUI elements. And now adding code to replace tokens with button prompts, (and in the future handle translations). I have some global events for when the input type is switched or language is changed, now I wonder if there's a way to somehow hook up to the tmp element's .text property getting assigned?
(I guess I could just have a "convention" that every time I assign text I run it through some code)

faint tree
#

yeh you could keep a list of them, and check if current text == originaltext, set new text

#

looks like i have a script on every text that can be translated, and a bool like isScoreText, which u tick, and then it knows it has to grab the translation of the score text

#

for example if (incomingNuke){ t.text = RSL_LanguageCollector.getFromCache(INCOMING_NUKE); return;}

#

then u find them all call method to update the text

frail dust
#

How do I make those gear interactions like shown in this video?
https://www.youtube.com/watch?v=KBEhmKxEvfQ

Welcome to our exciting tutorial on "Developing a Candy Crush Style Game in Unity 2D (2024)"! In this video, we'll guide you through the entire process of creating your very own match-3 puzzle game inspired by the popular Candy Crush saga. Whether you're a beginner looking to dive into game development or an experienced developer wanting to expa...

▶ Play video
faint tree
#

quite a lot going on, they must all be separate sprites with anims

frail dust
faint tree
#

looks like it will be explained in that tut

frail dust
faint tree
#

ah dont know then, either in unitys anim tools or using an artist 🙂

gloomy smelt
wintry crescent
#

is there a way to override (or block) the parameterless constructor of a struct?

#

here's my issue

#

my workaround is this

#

but doing something like
new HexGrid()
doesn't actually use that constructor, it uses the default 0 parameter one that sets all variables to their default

#

and I want to set some variables when calling that constructor with 0 parameters

#

so I need to call new HexGrid(0) to get my desired constructor but that's silly

somber nacelle
# wintry crescent

no, unity's version of c# does not allow declaring a parameterless constructor on a struct

wintry crescent
#

do I REALLY have to wait till unity 7 for this to be properly fixed?

#

insane

somber nacelle
#

there is not because a parameterless ctor on a struct is supposed to create an instance of the struct with all of its bits at 0 (meaning all of its fields are at their default value)

wintry crescent
#

annoying as hell but I guess I can't do anything about it

#

or is there a way to like disable that constructor

#

parameterless constructor

somber nacelle
#

c# went 20 years without being able to declare a parameterless constructor. i'd say "supposed to" is accurate

quartz folio
#

It's a year old feature in a 24yr old language

wintry crescent
#

c++ has it since forever

knotty sun
#

there is a simple way to solve this problem, dont use c# if you don't like it

leaden ice
# wintry crescent insane

Believe it or not language designers have multiple competing priorities and this one just wasn't that important

somber nacelle
wintry crescent
#

I guess I just have to deal with it until unity 7 brings us sanity

leaden ice
#

It's really not a big deal

wintry crescent
#

¯_(ツ)_/¯

mental rover
#

but it's just syntax preference

thin aurora
leaden ice
#

Like, some languages don't even have constructors and they get along just fine. For example Go.

faint tree
#

never even noticed c# not allowing empty constructor

thin aurora
# wintry crescent my workaround is this

Also, even better; make a static property + field that represents the "default" value here. Considering you don't have parameters it makes no sense to create a new instance every time. If it's mutable, then have the property return a new instance every time

#

This is even more common

somber nacelle
faint tree
#

ah that explains it, i never use structs

#

argh i tweaked something and platforms all changed in every level wtf.

somber nacelle
#

if you modify a prefab, then all of the instances of that prefab will also change unless what you modified was overridden by an instance. then it won't change on that instance