#archived-code-general

1 messages · Page 291 of 1

worthy fable
#

I'm trying to make a save system for the game. I want to read data from more than one script and throw this data into a json file.
Tried something like this :

data = new PlayerData(_playerExperience.currentLevel, _playerExperience.currentExperience,
    _enemyValueSet.enemyToSpawn, _playerAttack.playerDamage);```
But I can't reach any of the data.
dusk apex
worthy fable
#
_playerExperience = new PlayerExperience();
_enemyValueSet = new EnemyValueSet();
_playerAttack = new PlayerAttack();```
This code was generated by copilot and it's not possible to assign this way since MonoBehaviors can only be created using AddComponent()
#

And I can't find another way to achieve this

lean sail
#

Just make it a regular c# class

worthy fable
#

PlayerData isn't a MonoBehaviour, Other scripts are.(PlayerExperience,EnemyValueSet,PlayerAttack)

lean sail
#

If you need to save specific values on the monobehaviour, still just use that script to return its data in a regular class. That class can contain only relevant data

dusk apex
worthy fable
dusk apex
#

You'd just add new components.

worthy fable
#

Creating new components using current values set while playing.

lean sail
worthy fable
#

Because of the way I referenced each script

lean sail
#

Yes but you've in the same message written the solution..

worthy fable
#

I think its the problem not the solution

lean sail
#

If you're trying to reference an existing script, then either use GetComponent or drag it from inspector. If you need to add a new script, use AddComponent

lean sail
#

"Since monobehaviours can only be created using AddComponent()"

worthy fable
#

Wait so _playerExperience = GameObject.Find("Player").GetComponent<PlayerExperience>();
would work just fine?

dusk apex
#

Oh god, this looks ai generated.

lean sail
#

Yea..

worthy fable
#

Wdym its me writing it

lean sail
dusk apex
#

You wouldn't need to necessarily Find anything if you're passing references. Nor would you need Get Component if the references are passed as the correct initial types.

worthy fable
lean sail
#

Down the line, one script is eventually gonna have to inherit from a monobehaviour. Pass the reference directly into there through inspector

dusk apex
#
var instance = Instantiate(...);
var whatever = instance.AddComponent(...);
whatever.init(...);```
#

I'm assuming the issue is with wanting to initialize the component using the constructor where instead with components this would have to be done afterwards - in some sort of method.

worthy fable
#

I think I was confused by not being able use Start() method and not knowing where to assign those script references.

vale bridge
#

Is this a good way to fire weapons? For context I have an inputmanager script that uses the inputActions feature. Gun will be on a child of the player

private void Start()
    {
        gun = GetComponentInChildren<Gun>();
        if (gun)
            onFoot.Shoot.performed += ctx => gun.FireWeapon();
    }
#

I didn't want to do the input.getKeyDown directly in the update script for the weapons

cosmic rain
#

And having it subscribed as an anonymous method makes it difficult.

vale bridge
#

I'll do it explicitly then, thanks for the input!

#

Can you get a broadcaster like the gun is in this scenario to unsubscribe all the observers?

#

Is that possible?

#

If not how do you usually go about unsubscribing the observers in case an object is destroyed

cosmic rain
#

Each observer would need to unsubscribe itself. Somewhere in OnDisable or OnDestroy

wary coyote
#

Something completely inexplicably is going on in my unity project and I am not sure how to diagnose it let alone fix it.
The problem: An attribute is no longer drawing in Inspector when I booted my project this morning. Now its just gone from inspector. No console errors, compiles just fine, but its gone.

Things ive done to try to fix it:

  • Restarted unity, restarted my PC, reimported all assets, deleted the library and cache, a cloned new version of the github repo from scratch, reinstalled that version of unity from scratch

A friend was able to pull my repo and its there for them but its not there for me

#

I've run out of things to try to get this working, I rolled back to earlier commits in the github to a time when I know 100% it was working, and its no longer working

#

The inspector attribute that is broken was also broken in a brand new project made from scratch that I ported just that code into, except its NOT broken in this other project, and its not broken in the github pull my friend did of the same version where it is broken

#

What else can I do? How do I fix this?

leaden ice
wary coyote
# leaden ice Maybe share the code for the property drawer?

Sure, it hasnt changed in months though so I am not sure how its relevent given that nothing about it has changed so for it to suddenly stop working despite unity not changing variables and not being rewritten or anything else occuring

using UnityEngine;
using System;

[AttributeUsage(AttributeTargets.Method)]
public class ButtonAttribute : Attribute
{
    public string ButtonName;
    public RectOffset Padding = new RectOffset(5, 5, 3, 3);


    public ButtonAttribute(string buttonName = null)
    {
        ButtonName = buttonName;
    }
}   ```
#

Attribute, and drawer:

#
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;

#if UNITY_EDITOR
[CustomEditor(typeof(MonoBehaviour), true), CanEditMultipleObjects]
public class ButtonAttributeDrawer : UnityEditor.Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();


        var mono = (MonoBehaviour)target;
        var type = mono.GetType();

        foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
        {
            var attribute = (ButtonAttribute)Attribute.GetCustomAttribute(method, typeof(ButtonAttribute));

            if (attribute == null)
                continue;

            string buttonLabel = method.Name;
            if (!string.IsNullOrEmpty(attribute.ButtonName))
            {
                buttonLabel = attribute.ButtonName;
            }

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();

            GUIStyle style = new GUIStyle(GUI.skin.button);
            style.padding = attribute.Padding;

            Vector2 size = style.CalcSize(new GUIContent(buttonLabel));

            if (GUILayout.Button(buttonLabel, style, GUILayout.Width(size.x + style.padding.horizontal), GUILayout.Height(size.y + style.padding.vertical)))
            {
                method.Invoke(mono, null);
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
        }
    }
}
#endif```
#

it makes a button of a method if you put the [button] tag over the method. Its not about what it does, its about why did it randomly stop working all on its own suddenly despite nothing changing, I feel gas lit

#

Its immensely confusing that the buttons appear on other people's pulls of my repo and not on mine

quartz folio
#
  1. Is your inspector actually running
twilit scaffold
#

Why does it not show me where Config is coming from, like it shows me this information..

#

is this a configuration problem, or am i just expecting too much from VS?

#

Even if it just showed me the Defnition Peek, or even just the File it is coming from, on hover, that would be very helpful to my failing memory as i learn this stuff

latent latch
#

Been testing some scenarios using physic queries (specifically OverlapSphere), and I've noticed that applying a layer mask to filter out colliders doesn't actually increase the performance of the query. I've double checked and made sure no colliders were being added to the designated array, so it's not like the mask it being applied incorrectly. So, is that just the nature of these queries or perhaps there's something else I'm missing here.

dawn nebula
latent latch
#

is 100k enough

dawn nebula
#

Probably, ya.

latent latch
#

very little difference from collecting the colliders vs not* populating the array

#

probably going to make a test for distance collection of colliders and see how well that performs now

dawn nebula
#

Are you using the non-alloc version too?

latent latch
#

ye

dawn nebula
#

🤷‍♂️

latent latch
#

it's being tested on a per frame basis, so gc less of a problem

dawn nebula
#

another mystery of the engine

#

I guess it really depends on how physics queries are handled under the hood

latent latch
#

time to render games using two cameras at different space in the world

#

so queries dont overlap

lean sail
lean sail
latent latch
#

Instantiated all gameobjects with only a colliders -> yielded a frame -> cast onto the area with and without mask relative to the gameobjects

twilit scaffold
latent latch
#

probably should boot up some python print some data to graphs

#

but yeah, the benefit overall is filtering out the indices to iterate over

lean sail
twilit scaffold
#

yeah, could be. thanks for the input though

latent latch
#

what's interesting though is that multiple queries in the same vicinity didn't increase linearly, so there's more going on than I thought

lean sail
twilit scaffold
lean sail
#

i love pressing f12 😅 feels nice to do it like im hitting the secret decompile button sometimes

latent latch
#

maybe ill try fixed but I dont think that would matter?

lean sail
#

ah if it was every frame then that makes more sense

#

i misunderstood, thought it was spawn -> wait 1 frame -> check

latent latch
#

oh yeah I do wait a frame after check instantiating, just for the heck of it

#

just want to run the query on a frame that isn't doing any other work

#

Without mask:

Num Type Groups & Overlap Operations: 1
Current Clusters: 98000
Elapsed time: 1.175700 ms

Overlap test #99
Num Type Groups & Overlap Operations: 1
Current Clusters: 99000
Elapsed time: 1.172100 ms

Overlap test #100
Num Type Groups & Overlap Operations: 1
Current Clusters: 100000
Elapsed time: 1.171900 ms

With mask:

Overlap test #98
Num Type Groups & Overlap Operations: 1
Current Clusters: 98000
Elapsed time: 1.196900 ms

Overlap test #99
Num Type Groups & Overlap Operations: 1
Current Clusters: 99000
Elapsed time: 1.196600 ms

Overlap test #100
Num Type Groups & Overlap Operations: 1
Current Clusters: 100000
Elapsed time: 1.228500 ms```
#

And here's the interesting one:

Overlap test #98
Num Type Groups & Overlap Operations: 5
Current Clusters: 98000
Elapsed time: 1.568400 ms

Overlap test #99
Num Type Groups & Overlap Operations: 5
Current Clusters: 99000
Elapsed time: 1.459900 ms

Overlap test #100
Num Type Groups & Overlap Operations: 5
Current Clusters: 100000
Elapsed time: 1.480000 ms

5 queries in the same frame for 5 different layers/layer mask divided evenly in the same vicinity

thorn stirrup
#

What is a good way to solve this?

When a player is airborne and collides with a platform, their character grabs on to the the platform, and jumps on.

So if the player collides with the bottom of the platform(bottom of the box collider), an animation is triggered for the character, but their position is also moving (lerping) to the top of the platform, directly above their collision contact point with the bottom of the platforms box collider. .

If the player collides with a side of the platform/ box collider, the character locks on to the side of the platform, and lerps directly up and a small amount towards the center of the platforms top edge of the box collider

twilit scaffold
tall summit
#

someone can help me? im hosting an api in versel free and when I use thunder client to look if is working and it is works well, but when I use in UnityWebRequest it get an error of Authorization (401). I dont understand why... here some prints.

old linden
#

Hi, how can I access a Value with key in Newtonsoft JSON? It seems I have the syntax wrong though I can see the Key I am using is correct

thin aurora
#

Right now it's implicitly casted to JToken

#

Newtonsoft does these things because the whole system is for dynamic JSON without an explicit type, to make it easier

#

If you actually know the JSON returned you should not use this. Do you know the JSON format returned?

old linden
#

Thanks. It's for JSON files which are planned to follow the same layout but contain totally different values. I've not used JSON before so it's all new to me

thin aurora
#

Actually, don't change JToken to JTokenKeyedCollection, because this is the base type for the collection in the foreach, so just change it to var, or try to find out what the type of a value in JTokenKeyedCollection is by looking at the definition

#

If you can't get Keys like this make sure to cast it to a JTokenKeyedCollection first

old linden
#

Thanks but I'm iterrating over a JArray not a JPropertyKeyedCollection

thin aurora
#

But the entry in this array is a Dictionary right? You wanted the key of these?

#

That's what I assumed judged by the image you shared

old linden
#

I'm not exactly sure. All I know is I have a JArray and I'd want to get access to the Values with the Keys in the debugger 😦

fervent furnace
#

I wonder why you cant make a poco in c# side….

thin aurora
#

Do the keys and values exist in the array?

old linden
#

@thin aurora
Hmm. Here is my Json file and more of my code. I'm trying to return the "Item" fields value as shown in the image. JArray jsonArray is the groups of fields I get using sheetname which is set as "Export Master" for now. Apologies I am a little useless with the entirety of json

thin aurora
old linden
#

Yes, though the check near the top should account for that

thin aurora
#

Then you should just iterate the array, and each entry has a "item" property you can check

#

Can you share the !code through a text editor?

tawny elkBOT
old linden
#

.Item[string] property is for a JObject, but I have a JArray 🤨
Sure give me a min

thin aurora
#

The JObject will then return the value as a JToken, and you can then get the value from this using Value<T>

#

T being string in this case

chilly surge
#

Do you know the array is always named Export Master? I think someone already answered you before that if you have specification of the format, you wouldn't need to manually traverse the JSON with dynamic API.

thin aurora
#

I don't think it is judging by the variable but this is better answered by them

old linden
old linden
lean sail
#

whats the use case of this if you dont mind as well? because if you had a class that contained the needed fields, this would be a very simple 1 liner

chilly surge
#

You are basically reinventing (the most used part of) Newtonsoft.

old linden
#

Working for a company which has no idea is bad haha

lean sail
#

if there is possibility of change, then you cannot guarantee the field will be named "Item" forever, thus this breaks as well

thin aurora
# old linden <@191282187016863744>
JObject json = JObject.Parse(File.ReadAllText(Path));
jsonArray = json[sheetName] as JArray;

if (jsonArray == null)
    return;

foreach(var entry in jsonArray)
{
    var item = entry["item"].Value<string>();
}
#

This might also work

JObject json = JObject.Parse(File.ReadAllText(Path));
jsonArray = json.Value<JArray>(sheetName);

if (jsonArray == null)
    return;

foreach(var entry in jsonArray)
{
    var item = entry.Value<string>("item");
}
#

Keep in mind all of this is dynamically generated and there is no guarantee these things exist, so you should always apply proper null checking in the event the json ends up different

old linden
thin aurora
#

Also, can the array entry contain different data or is this always the same?

thin aurora
old linden
#

The more I look at this, the less likely I am going to suggest it for my project. The company effectively want something with a non-fixed layout which I see won't work

thin aurora
#

What exactly in this json can vary in terms of naming and data? The whole system should only be like this if the JSON is varied, but what exactly is varied here?

#

You could probably cut off a lot of this parsing if the data is always the same

old linden
#

Literally everything

#

Sheet name, list of fields, their names

thin aurora
#

Right then I doubt this can be done any better unless you can serialize it in a class where data is nullable

old linden
#

Ok thanks

lean sail
old linden
thin aurora
#

It's kind of possible, it's just a lot of work when the JSON varies

old linden
lean sail
#

you can parse the data, but you wont use it

thin aurora
#

So generally you should not do that unless it's simple, like two different objects being part of an array

#

Anything more complex should perhaps be reconsidered

#

Yesterday I had to parse incoming data from Typescript, which is a lot more flexible when it comes to types, but this becomes a ton more complex in .NET

#

So I'm also going to change this around a bit probably

lean sail
#

im still super curious at what they were planning for this 😅

old linden
# lean sail im still super curious at what they were planning for this 😅

So we have a bunch of scenes loaded dynamically by a single project at runtime. They want to use JSON for scenes which have customsable data. So in the example of my Json file i shared, it was a supermarket with products, prices, weights and cost etc. The company either doesn't know or won't tell me what else they want to do with it but they said it must be able to adjust dynamically for different json layouts 😂

#

As you can imagine they have 0 technical knowledge

lean sail
#

i was actually typing something like that in my message above as a joke and deleted it, "a game built on json"

old linden
#

lol

old linden
thin aurora
#

Sorry, my experience with this got rusty after a while

old linden
#

No worries

thin aurora
#

This means that some variable ended up being a JValue, which you can't get another vlaue from unlike a Jobject

#

What is line 59?

#

My guess it's entry["item"].Value<string>(). Try entry.Value<string>("item"); instead

frail dust
#

hey there, anyone having good hands with Poisson Disc Sampling in unity? I need help

thin aurora
frail dust
#

alright

craggy veldt
#

is there a timer that's frame-rate dependent ? similar to Time.realtimeSinceStartup but that obviously would not slowing down if I forcefully lagging the game.
Of course we can roll our own elapsed time via deltatime, but hoping for something built-in instead

late lion
craggy veldt
#

huh, pretty sure I tested this 🤔.. let me check once again. Thanks!

frail dust
#

how do i even judge that whether the problem is a general problem or advanced or even a beginner

knotty sun
frail dust
knotty sun
#

rude? why was that rude? I was just answering your question

frail dust
late lion
eternal dome
#

Why is the function called only at a certain angle and not constantly when you touch the collider? The code seems to be correct

        RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, grabRadius, Vector2.right, 0);
        for (int i = 0; i < hits.Length; i++)
        {
            item item = hits[i].collider.GetComponent<item>();
            if (item != null) 
            {
                item.InRadius(true);
                Debug.DrawLine(transform.position, item.transform.position, Color.blue);
            }
            else
            {
                foreach (item _item in GameObject.FindObjectsOfType<item>())
                {
                    _item.InRadius(false);
                }
            }
        }
``` Code that calls a function in a radius
frail dust
#

Can you show your player's properties?

eternal dome
quartz folio
frail dust
frail dust
#

alright

#

what does the blue circle do?

#

the big blue one

eternal dome
eternal dome
frail dust
frail dust
eternal dome
#

that is, the player's collider will not affect this in any way

frail dust
#

so does this mean that whenever an item is in that blue circle, then only the player can interact with that?

frail dust
#

got it

eternal dome
#

This happened when I added several layers of tile maps. Maybe it has something to do with

frail dust
eternal dome
versed spade
#

Is there a better way to store object data for access in a CS script

#

Don't want to wastefully make an object just to call these values

heady iris
#

There are two options here

#
  • make a plain old C# class and mark it with [System.Serializable]
    • This isn't a Unity object, so it can't be referenced. You just directly embed it into something else.
  • make a ScriptableObject class and create assets to store instances of it
    • This is a Unity object, so it can be referenced like a MonoBehaviour or GameObject
#

Use the latter if multiple things need to share a reference to the same data.

#

Use the former if it's always (or almost always) unique

cerulean zealot
#

hi! is there a way to report a BSOD bug on this discord server?

mental rover
cerulean zealot
hard viper
#

that is an issue with windows

#

and even if it were a Unity issue, it would still not be a code issue, which is what this channel is about

cerulean zealot
#

I see, thanks

heady iris
#

It could be a GPU problem that Unity reliably triggers.

#

But that would still be something that should be reported elsewhere

faint tree
#

is there a way to access files outside the plugin folder, from inside it?

#

im using an asset for fingerprint scanning and when it succeeds i want to call a method on my main class but it wont let me import it

leaden ice
#

Typically such a library would include a way to handle the completion of scanning the fingerprint

#

Are you sure you're not missing something?

#

e.g. some kind of onComplete event, or an isCompleted property somewhere you can check.

faint tree
#

thanks for the help. yeh theres an Action successHandler which is called when my fingerprint is scanned successful, so to proceed i want to call fingerPrintScanned() on my main app class, but i cant import it to call that

leaden ice
faint tree
#

i see, how would i subscribe to it?

leaden ice
#

It's unclear

#

is it a parameter?

#

Or an event somewhere?

#

I would need to see how it's set up

#

if it's just a parameter you pass in - then you should simply pass in your callback and call it a day

faint tree
#

its like

#
    "Flow Valet Authenticate", "Unlock with finger or face", () =>
{
  
    // success
    MessageText.text = "success" ;
    _("SUCCESSFULLY UNLOCKED");
    
},
leaden ice
#

Ah yeah then you just pass in your thing there

#
jBiometricScript.StartAuthenticate( 
    "Flow Valet Authenticate", "Unlock with finger or face", () =>
{

    myMainClass.fingerprintScanned();

}```
faint tree
#

hmm, i cant import myMainClass, and that code is inside the plugin, i guess i could move that code into my main class

leaden ice
#

Where are you calling this from?

#

I'm trying to understand the interface between your code and the plugin code

faint tree
#

the code i pasted is inside a .cs file inside assets/plugins

leaden ice
#

is this code you wrote inside the plugin, i.e. you already have been making changes inside it?

#

at some point in your code you are accessing the plugin somehow, no?

faint tree
#

well i was attempting to hack in a line like u said myMainClass.fingerprintScanned();

faint tree
#

no im not accessing it from my main code

leaden ice
#

how are you even starting the fingerprint scan FROM YOUR CODE

leaden ice
#

You have to be, no?

faint tree
#

i copied the sample scene objects into my scene file

leaden ice
#

oh that's just example code

faint tree
#

which contains a button to start it

leaden ice
#

yeah you don't want to modify that

#

it's just an example

#

write similar code in your own scripts

leaden ice
#

it's just an example

#

samples are meant to be samples. They're not meant to be used in your project directly

faint tree
#

ah, i usually just bring them in and hack them a bit

#

🙂

#

ill try it cheers

#

awful that u cannot import easily

leaden ice
faint tree
#

yeh but i nearly always do lol

leaden ice
#

bad habit

faint tree
#

yes i suppose it is, for when u update it etc

crisp bronze
#

Hi, I'm trying to create a random level generator that uses prefabs and spawns them on a grid based on their proper entrances. Each spawned prefab should be chosen based on having a door that connect to the previous entry direction, and also based on its next available exit point. At the moment, I'm having trouble with making sure that the prefabs don't spawn on top of existing ones. Any ideas?

Here are my scripts so far:
LevelGenerator - https://github.com/jungaboon/JungaBoon-Utils/blob/main/Scripts/LevelGenerator.cs

LevelSegment - https://github.com/jungaboon/JungaBoon-Utils/blob/main/Scripts/LevelSegment.cs

leaden ice
#

are they all the same shape?

hard viper
#

Is there a way to make a property drawer for a generic class? I have EnumerableArray<TEnum, TStored>, and when the field is serialized, it is given a concrete type

crisp bronze
leaden ice
#

you say "to test"

#

what will it be in the final thing?

#

Will they be arbitrarily shaped 3D rooms?

#

You would probably benefit from some kind of regular grid system here

jagged snow
#

If you want to limit the scale of an object based on distance. Do you limit the distance or the scale?

What I'm trying to do is basically clamp the size of a floating text. When the camera is close I want it to stay at a certain size and vice versa

heady iris
#

you'll want to vary the scale when the distance is below a lower bound or above an upper bound

#

I think you'll just do this:

#
float distance = Vector3.Distance(transform.position, viewer.position):
float scale = normalScale;

if (distance < lowerDistance) {
  scale *= distance / lowerDistance;
} else if (distance > upperDistance) {
  scale *= distance / upperDistance;
}
#

I feel like this is missing something, though...

#

It makes sense up close. If it's halfway to the lower limit, you halve the scale.

But I'm not sure about the upper limit. It feels like I should be subtracting something here. Not sure.

#

But you could give that a try.

faint tree
#

@leaden ice works great now, thanks dude... fingerprint and facescan, very cool!

#

would be good if u could update the biometric data by downloading it for different users etc,

jagged snow
jagged snow
heady iris
#

so it's the "true" size of the object, I suppose

jagged snow
heady iris
#

if you double the distance, you double the scale

jagged snow
#

right but using your code which sets bounds that will limit it at some point right

heady iris
#

I thought you were looking for something more complex, whoops

heady iris
jagged snow
#

i actually dont want a certain size, it's more so that i dont want the text to become smaller when too far away and too big when close

#

I want to clamp the size at certain ranges, that would be a better question. Like the size of the text at 40 distance would be the same as it would be at 90

heady iris
jagged snow
faint tree
#

anyone use a qrcode scanning asset? just wondering which ones work well

heady iris
#

Take the ratio of the current distance to a reference distance (say, 10 meters)

#

That's how much larger or smaller the object looks than at the reference distance.

jagged snow
#

Im going to try this first. Everything functions normally until a certain distance is met. To not complicate things at the start ill just have it detect if the text is too far. Once it reaches this point enable the scale formula.

hard viper
#

my attribute cannot take the type of my generic argument, but it should be hard coded to the concrete class. Any workarounds?

mossy snow
#

are you sure? that looks like a syntax error to me

hard viper
heady iris
#

yeah, it looks like it has to be known at compile time (well, more than that, it needs to be a constant for this class)

#

I presume this is being used for some custom editor/property drawer code?

hard viper
#

yes

#

I have an EnumerableArray<TEnum, TStored> class which just maintains a strictly held array that relates an enum to TStored

heady iris
#

You could inspect the actual type with reflection.

ashen yoke
#

generics are generated at runtime, attributes are baked into meta on compile time

hard viper
#

ok, I'll see. I'm not very good at reflection tho\

heady iris
#

As long as it's always a TStored[] and not some arbitrarily complicated mess of generic types, it should be alright

hard viper
#

I'm honestly so lost right now, idk how to work with editor scripts.

heady iris
#

One important thing is to learn the division between:

  • unity's serialized data
  • the actual runtime objects
hard viper
#

I did get some code sent my way for a NamedArrayAttribute which I got working. The issue is idk how to reference the thing that the editor script is targetting

#
        // Replace label with enum name if possible.
        var config = attribute as NamedEnumArrayAttribute;
        string[] enum_names_compact = System.Enum.GetNames(config.TargetEnum);```
#

this is some of the code I got, and it works if I can get that target enum. But idk how to target the thing that I'm tied to

#

I think I might be able to take it from there if I could

heady iris
#

arrayElementType will give you the string name of the elements stored in a serialized array, which isn't quite what you need

hard viper
#

EnumerableArray contains an array, and I'm trying to give it an attribute, but I don't think this is enough information because the array doesn't know rthe enum

heady iris
#

but that's just going to give you a SerializedProperty holding an integer

hard viper
#

I can call isArray etc

#

but I need to know the type of the enum, which isn't in the array

heady iris
#

I'm kind of a novice here too, so this might be wrong.

I think you need to grab the serializedObject from property, then get targetObject and get its type.

Then you can search for a field whose name matches that of the original property and check its custom attributes for your NamedEnumArrayAttribute. You should also be able to figure out the generic type by fetching FieldType from the FieldInfo for the field.

#

Quite a mess.

glad plinth
#

Is it possible to calculate the "FPS" of this texture?
as that would be the FPS of the cloned screen

rigid island
glad plinth
#

This texture kinda technically would as its a screen mirror it updates to mirror your IRL screen

#

is there a way to get how frequently its doing this?

leaden ice
#

doubtful

#

but probably depends on this actual script or component or whatever

#

It's likely just reading some texture from a native buffer somewhere once per Unity frame

#

It's not likely caring or recording how often the "source" of that frame data is writing to the buffer.

visual wolf
#

i have 2 public double variables, i want to save them to a file and load them. i am thinking about using playerprefs, is that possible? I read somewhere that i'd have to convert it to a string to save it, and back to a double to load it.

glad plinth
rigid island
leaden ice
#

The third one is probably the best tbh

#

Make a proper save system

visual wolf
#

how do i do that 😭

#

i started unity only about a month ago so i'm fairly new, i'm not sure how to make a proper save system yet

#

i only need to save like 3 doubles

rigid island
visual wolf
#

data object?

rigid island
#

like a regular object, class

visual wolf
#

oh

rigid island
#
public class SomeData
{
    public double myDouble;
    public double myotherDouble;

}```
visual wolf
#

oh

#

that seems quite easy

#

is that it?

#

and then serialize and whatnot

rigid island
#
 public static void Save(SomeData data)
    {
        var stringData = JsonUtility.ToJson(data);
        var path = Path.Combine(Application.persistentDataPath, "theFile.data");
        File.WriteAllText(path, stringData);
    }
visual wolf
#

and then what?

rigid island
#

thats pretty much it

#

you read it, do the inverse

visual wolf
#

really?

rigid island
visual wolf
#

wow i thought it would be a lot more complicated lol

#

can you do File.ReadAllText ?

rigid island
#

indeed 🙂

visual wolf
#

alright, i'll try get this done tonight, thank you very much for your help!

rigid island
#

sure thing! lmk if you have any issues

visual wolf
rigid island
visual wolf
#

alright lol

rigid island
#

you can reply me here or make a thread

visual wolf
#

ok, so i'm just super confused 😭

rigid island
#

oh alr. make a thread , I'll explain

hard viper
#

when throwing errors, is there a way to make my error have a string for the file + line of code for a given line that is being evaluated?

past tapir
#

also your console in Unity already shows the file, line # of the error

hard viper
#

that's not good enough

#

I am throwing an error on an invalid save. I am referencing things through an interface. The interface has a method to output a string with error message if it fails a check. These methods are only supposed to return true/false with out of an error message, and not necessarily throw.

#

I need to append the file+line# to the string of origin.

somber tapir
#

I use this AnimationCurve to calculate the required exp, but once the player reaches the "estimated max level" the required exp no longer increases. Is there a way to have the curve go on infinitely?

chilly surge
# hard viper I need to append the file+line# to the string of origin.
past tapir
#

you can also try "Ultimate Editor Enhancer" it will put a (!) on any game object that throws a error

latent latch
#

It's not like you've some linear values to just plot that easily either, so if you do want this exponential gain then that's something you'd have to put together and plot dynamically, or just throw the equation in code.

heady iris
#

An exponential function for EXP per level is pretty simple.

#

or maybe something polynomial

#

Desmos is great for playing around with functions for this purpose.

magic wolf
#

Dumb question. How do I change the scale of an animation? I have a player object with several animations. Walking jumping ect. Well when he is idle he is normal size but as soon as it uses another animation he grows to about 2.2 times the normal size

heady iris
#

Did you make these animations yourself?

#

If not, did they come from different places?

magic wolf
#

No

#

They all came from the same sprite sheet

#

I didn't personally make them but they were made for me

heady iris
#

ah, these are sprite animations

#

can you adjust the pixels-per-unit on individual sprites sliced from the same image? if so, that might be the issue

#

(i've just recently started learning 2D)

magic wolf
#

I think so

#

Do I lower it? or raise?

heady iris
#

make sure they are consistent

magic wolf
#

oh ok

#

I will try

heady iris
#

Reducing the PPU means the sprite is larger in the world

#

since you need fewer pixels to cover one unit

magic wolf
#

Oh you know what... I messed up

#

I took a week break and was mid swapping animations. Not all of them are swapped and I forgot 🙄

#

Sorry Im dumb

heady iris
#

Ah, that'll do it :p

magic wolf
#

Thats what happen when you sleep :p you forget stuff

#

lol thanks for the help haha

spice briar
#

hey, so im making a scope system for my game with variable optics, Basically, i need a way to convert a zoom multiplication (i.e. 4x scope) to the camera FOV that i need to zoom to. any ideas on how to do this>

leaden ice
#

e.g.:

float GetFOVForMagnification(float baseFov, float magnificationLevel) {
  return baseFov / magnificationLevel;
}```
#

baseFov would be the FOV you consider for the "1x" zoom level

spice briar
#

makes sense, thanks!

leaden ice
#

by the way unless you need perfect physical accuracy for some strange reason, It's also completely valid just to play with the actual FOV numbers corresponding to each zoom level until it "feels right"

spice briar
#

well its intended to be a realistic shooter

cold adder
#

Hey y'all, I'm starting to design a 4 player RPG game, but I don't know where to start for game servers, anyone have any tools they'd reccommend?

rigid island
weary swift
#

Yo ! Is error handling/exception handling a useful thing to do while developing your project ?

rigid island
#

Imagine you're looking for a File to read from, but the file doesn't exist. How would you communicate that without handling a custom exception to show a neat window "Save File Not Found" or something

#

also you wont break the rest of the code possibly , just cause file is not found

weary swift
#

And do you remove all the error handling before making the final build of your game ?

rigid island
#

that would defeat the purpose

#

this isn't to say you need to make everything an error to handle or a try Get

weary swift
#

Because you may need to add features, or correct bugs or anything like this right ?

weary swift
rigid island
#

to me error handling is more important in things beyond my control

weary swift
#

Ok

heady iris
#

Exception handling is for things that are both:

  • things you expect to happen
  • things you can reasonably deal with
rigid island
#

eg Internet Requests, File movement / creation etc

#

maybe you have an Upload to internet rquest, it may work on your PC but you have to handle if case there is no connection / error

weary swift
#

Ok, maybe I didn't use the right term. What I mean is for example checking if a scriptReference is null before using it

rigid island
#

oh those are just null checks

#

they arent errors unless the item is null and you try to use it

weary swift
#

Then my question is should I null check "everything" or should I trust myself/others to put the rights values in the code so that it works ?

#

Because even if there is a null error the compiler will alert me

weary swift
heady iris
#

These errors happen at runtime.

rigid island
weary swift
#

I'm talking about the LogError that appears when there is a null reference

weary swift
#

I think that's precisely my question

#

If I understand what you said, I should null check if I can do something with it right ? If not then I just let Unity LogError

neat forge
#

This is mostly a question of coding style/philosophy

rigid island
weary swift
#

Yes

rigid island
#

but if you know it wont be null there would be no need ofc

weary swift
#

But, if the only possibility that it is null is because a human made an error while giving the reference to the script in Unity inspector for example. In this case, should I check ?

wicked scroll
weary swift
#

Ok, makes sense

neat forge
#

In my opinion, "failing loudly" is the way to go. If you're giving a method a parameter and you null check it and it does turn out to be null, but the method needs this parameter to do its work, what are you going to do? Just silently not do it? Then you're just making your bugs harder to find

wicked scroll
#

there's also the 'null object pattern' which can be useful so that you never really have nulls

rigid island
#

@neat forge well yeah, just depends what that object is

#

if you have private List<string> myList = new()
obv you dont need to check myList being not null because it always guaranteed it wont be

weary swift
#

I'm going to give a concrete example. I have an animation for a weapon and have two floats, one is the "hitBoxStartTime" the second "hitBoxEndTime", theses two floats are time contained in the animation that tell me when the hitBox should be enabled and when the hitBox should be disabled. Ofc the Start should be less than the end.
So I wrote this :
if (!(attackAnimationData.hitBoxStartTime < attackAnimationData.hitBoxEndTime))
{
Debug.LogError("HitBoxStartTime should be less than HitBoxEndTimer.");
yield break;
}

But I feel like it's serve like no purpose, the only case in which this would happen is if a human made an error while declaring the variables.

#

This isn't a null check but I guess it's in the same ideas

knotty sun
wicked scroll
weary swift
#

filled via a scriptable object

weary swift
wicked scroll
#

yeah, for something like that i would say to do validation in the SO itself so that by the time that data gets to the game, you know it's correct (and so that you can do stuff like have a message saying HEY YOUR VALUES DON'T MAKE SENSE at design time when it's useful)

#

'creating content for your game' and 'running your game' are different contexts and you can totally take advantage of that

weary swift
#

So, while creating content for my game, let's say in this case creating attack animations, I should make some Debug in case I fail in the design process. But when the design process is finished, I should remove these because they serve no purpose anymore right ?

#

Or I can just trust myself that I don't input wrong values

#

It's just preference ?

wicked scroll
#

i would consider that design is never really 'done' and that it's wortwhile to assume that maybe some day you'd want to change a number or whatever and have your validation still be in place

#

it doesn't hurt anything to keep it in there since it's all 'editor' stuff

knotty sun
wicked scroll
#

there's also compilation hooks you can use to check that certain values are filled in/valid/etc when you do a build

weary swift
weary swift
wicked scroll
#

built into unity

weary swift
#

Ok, thanks for all the answers guys ! Really helpful, I appreciate this.

wicked scroll
#

if you find something wrong you can throw a BuildFailedException and it'll abort your build with the error

#

so you can do stuff like make make sure your config assets are properly filled in or whathaveyou

heady iris
#

I guess it'd be nice to run that before the build, though :p

#

that'd be IPreprocessGroupWithReport, then

wicked scroll
#

oh yeah there probably is a before one too if that'll work for your (i imagine it would for most cases)

heady iris
#

Definitely looks useful -- I have a few things I'd like to be a hard fail

#

like a scene that my game lets you visit not actually being in the scene list

wicked scroll
#

yeah! i don't use it much since mostly it makese sense to validate things more...in-place? but where it's nice, it's nice

heady iris
#

this has made new features a lot easier to set up for all of my existing entities

#

(when the new feature results in serialized fields appearing on existing components, that is)

#

ideally most new stuff is just a new component

hoary sorrel
#

I'm having an issue where my game works fine in the editor, but when I build it, a lot of the references stop working, and the game becomes unplayable. Enemies are no longer killable and the game over screen no longer displays half of the required elements.

latent latch
hoary sorrel
rigid island
#

thers an asset

hoary sorrel
hoary sorrel
#

thank you

rigid island
#

check console for errors

hoary sorrel
golden garnet
#

Does anybody happen to have any answers for this?

rigid island
#

like code

#

setup

#

etc.

rigid island
golden garnet
#

I could send a video, if that helps?

rigid island
#

yes but code would probably help..

hoary sorrel
rigid island
hoary sorrel
#

would a video of the issue help?

rigid island
hoary sorrel
#

can you explain what you mean by "click on enemies"?

rigid island
#

oh sorry i read Killable as Klicable

#

dyslexic af

hoary sorrel
#

all good

golden garnet
hoary sorrel
rigid island
#

how can you say "No errrors"

#

12 errors by end of video

hoary sorrel
#

i'll show you what the error log looks like

rigid island
#

so how do you know that is not breaking the rest of the execution

hoary sorrel
#

just a whole bunch of that

rigid island
#

why is it looking in System32..

#

anwyay its happening mid killing enemy at some point

#

so you have to show that method

hoary sorrel
#
    private void Start()
    {
        highScore = System.Convert.ToInt32(System.IO.File.ReadAllText("highScore.txt"));
    }
    public void updateScore(int amount)
    {
        score += amount;
        scoreText.GetComponent<Text>().text = "SCORE: " + score.ToString();
        highScore = System.Convert.ToInt32(System.IO.File.ReadAllText("highScore.txt"));
        if (score >= highScore) { System.IO.File.WriteAllText("highScore.txt", score.ToString()); }
cold adder
rigid island
rigid island
hoary sorrel
#

yeah

#
    void enemyDie(int scoreChange, bool heartDrop)
    {
        if (!enemyCountUpdated)
        {
            spawnerScript.enemyCount -= 1;
            enemyCountUpdated = true;
            logic.updateScore(scoreChange);
            int rng = Random.Range(0, 9);
            if (rng <= 1 && heartDrop) { Instantiate(heart, enemy.transform.position, enemy.transform.rotation);}
            if (heartDrop) { sound.playSound("enemy"); }
            Destroy(enemy, .2f);
        }
    }
#

logic.udpatescore is called as normal so its only an issue with the destroy method

rigid island
#

to me this just makes it more clear that if one of those is null/throw error Destroy will not reach

hoary sorrel
#

one of what is null?

rigid island
#

not null but if they throw error rest of code might not run

#

first id try making new build without logic.updateScore(scoreChange);

#

see if that helps then you narrowed down issue

hoary sorrel
#

alright

#

wait that actaully worked

hoary sorrel
cosmic rain
rigid island
#

ur not passing a good path

cosmic rain
rigid island
#

you should save to Application.persistentDataPath for example

#

this works with all platforms

simple egret
#

Also don't write to the file each time you change the score, IO operations are slow compared to other game code

hard viper
#

pretty sure those are the worst operations computers really do. worse than memory allocation

arctic orchid
#

Anyone wanna help me make a game?

rigid island
tawny elkBOT
open sparrow
#

Hi! Is there any alternative to animation events? I'm currently using them to enable and disable a collider who is responsible of dealing the damage. Since the animation can get cancelled the "disable collider" function might not be called. I can add a behavior to the animation state and disable the collider "on exit state". Is there any other way of synchronizing code with animations? Is there any other common workflow that is not animation events. Thanks and sorry for my English!

compact spire
#

Every time I start a new project I end up with a bunch of controllers with the urge to make them all singletons. Should I just embrace this direction or is there a better pattern to follow?

rigid island
#

using 1 thing to access many things is neater n easier to follow for me

#

forgot what the pattern is called, I think manager/mediator pattern or facade ?

thick terrace
lean sail
cold parrot
# compact spire Every time I start a new project I end up with a bunch of controllers with the u...

The most practical pattern for small teams/solo is to have your dynamically spawned objects use a service locator to register themselves with a static system/controller (loaded with the scene) which then proceeds to inject dependencies, init state and call event handlers on the dynamic objects IoC style. If you restrict service locator usage to this lookup and keep all service registrations immutable after startup this eliminates most negatives of such global-access patterns.

compact spire
#

@cold parrot I have a rough understanding of what your talking about, but I can't picture how that all ties together... Do you know of a good example or tutorial on that kind of setup?

latent latch
#

game manager

cold parrot
thick terrace
#

the requirements are pretty different per game too, you might go in a different direction for something very simulation and physics heavy vs a turn based game that's got a million UI screens

latent latch
#

It's like, you can make AudioManager a singleton (makes sense honestly), or keep it as a non-singleton mono and give gamemanager a reference to it

cold parrot
#

so there are a few things you can do to avoid the worst effects of singleton abuse and just overall inconsistent architecture or fighting the engine

#

things like zenject or vcontainer solve nothing if the fundamental issue of architecture is not understood in the team

thick terrace
#

there's always some trade offs to make though, it's impossible to get everyone to agree on the one universal best way which is why there's not much literature about it i think

dim relic
#

can someone tell me if anything is wrong with this movement script cause for some reason whenever i try to move in my game it just randomly stops and starts again and i dont know why

#

!code

tawny elkBOT
cold parrot
#

That is true. But still you can decide quite easily what’s a bad idea just based on scope of the project, with some minor thinking and awareness of options you have.

dim relic
latent latch
#

Posting a chunk of code like that without any logging isn't helping us here

dim relic
#

you have to press the fulscreen button next to expand

#

than you can see all the code

heady iris
#

Yes, it's 10KB of code with no additional information

#

What have you done to debug it?

cold parrot
compact spire
#

@cold parrot Fair enough, I'll have a look around then

dim relic
#

well i used a script from dani

#

whenever i walk with it it just randomly stops me for no reason

#

like it just starts going really slow and even starts puching me back

cunning gulch
#

when i change the tiles of my tilemap programatically it doesn't affect the tilemap collider at all, is that intended?

calm echo
#

@compact spire a good first step is to avoid naming anything with manager unless absolutely necessary

cold parrot
# compact spire <@544260011430248467> Fair enough, I'll have a look around then

The key I think is to gain a really good understanding of why global access is very bad, how to avoid it and some discipline that keeps you looking for better options. There is virtually no reason to have global access or invasive coupling to a framework for anything but the most superficial discovery. Also don’t fight the engine and use patterns that ignore the nature of unity/gamedev.

rigid island
cunning gulch
cunning gulch
#

ah yeah that works, thank you

rigid island
#

start debugging

#

I would just remake eevrything with Code and Tweening

#

I hate using animations now 😛

#

I like to control all my states

#

send script !code

tawny elkBOT
rigid island
#

oh god please dont use this site next time

#

use the ones provided by bot msg

#

half the page is "Advertisement" realestate

#

thx

cold adder
#

You can also just do tripple back ticks here

"```c#`
Code here

#

ah shoot

rigid island
#

not for large classes

#

use links for large code

cold adder
#

fair

rigid island
#

pls dont

cold adder
#

If they're big it usually makes it so they're expandable

#

I guess I'd hope they'd turn down the threshold fro that

rigid island
#

nah it cuts the lines off it says "x amount of lines remaining"

#

also on mobile it only shows as link to the file.txt

#

maybe switch it to animator ?

#

because it will surely making managing state easier first of all

#

this will be literally 1 bool on animator

#

basically you make a parameter is animator called Options or something

#

that is of bool type

undone plover
rigid island
#

then transition between the two clips with that bool

rigid island
#

this is a code channel

undone plover
#

sorry

rigid island
#

oh is working ?

#

I was thinking more like this

#

so you didnt have to use name of clips

#

hmm. yeah how are you starting the clips

#

I usually turn of also exit time for these if you want to spam and go up n down, thats why i suggested only a bool

#

instead of animator.Play

shell bridge
#

I need help with something

#

Spaces don't show

shell bridge
#

!code

tawny elkBOT
shell bridge
#
            {
                top_prefix = "";
            }
            else if (top_prefox == 1)
            {
                top_prefix = "THE*FOX*";
            }
            else if (top_prefox == 2)
            {
                top_prefix = "FOX*";
            }
            else if (top_prefox == 3)
            {
                top_prefix = "MISSPELT*";
            }
            if (rig_prefox == 0)
            {
                rig_prefix = "";
            }
            if (rig_prefox == 1)
            {
                rig_prefix = "THE FOX*";
            }
            if (rig_prefox == 2)
            {
                rig_prefix = "FOX*";
            }
            if (rig_prefox == 3)
            {
                rig_prefix = "MISSPELT*";
            }
            if (top_option == 0)
            {
                top_dis = Rnd.Range(0, foxes.Count());
                top_display.Add(top_prefix + foxes[top_dis]);
            }
            if (top_option == 1)
            {
                top_dis = Rnd.Range(0, misfoxes.Count());
                top_display.Add(top_prefix + misfoxes[top_dis]);
            }
            if (top_option == 2)
            {
                top_dis = Rnd.Range(0, twoletfoxes.Count());
                top_display.Add(top_prefix + twoletfoxes[top_dis]);
            }
            if (rig_option == 0)
            {
                rig_dis = Rnd.Range(0, foxes.Count());
                right_display.Add(rig_prefix + foxes[rig_dis]);
            }
            if (rig_option == 1)
            {
                rig_dis = Rnd.Range(0, misfoxes.Count());
                right_display.Add(rig_prefix + misfoxes[rig_dis]);
            }
            if (rig_option == 2)
            {
                rig_dis = Rnd.Range(0, twoletfoxes.Count());
                right_display.Add(rig_prefix + twoletfoxes[rig_dis]);
            }``` I used asterisks for spaces
lean sail
shell bridge
#

all the code?

rigid island
#

yes preferably in a link

#

this method is like insane

shell bridge
#

That's the code so far

rigid island
#

shit at least use a string builder..

#

anyway what exactly you mean by spaces dont show

shell bridge
rigid island
shell bridge
#

It uses the code

#

It should say MISSPELT FY

#

So how would I make spaces work in the code

#

It works in Unity

#

So should I do no spaces or no?

rigid island
#

I haven't a clue what your code is supposed to do

shell bridge
#

It is for a Keeping Talking and Nobody Explodes modded module

lean sail
shell bridge
#

ok

wild spire
#

Hello everyone. I have been looking into mesh deformation in unity and have gotten this script. It deforms a plane mesh to curve to a sphere mesh. However when trying to apply this script to my blender face mesh, it does not work, since its built for spheres. Anyone have any ideas how I can refactor this script to work on low detailed mesh like this?

    public float hoverDistance = 0.1f; 

    void Update()
    {
        Mesh mesh = GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;

        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 worldVertex = transform.TransformPoint(vertices[i]);
            Vector3 directionToSphere = (worldVertex - sphereTransform.position).normalized;
            float sphereRadius = sphereTransform.localScale.x * 0.5f; 
            Vector3 newPosition = sphereTransform.position + directionToSphere * (sphereRadius + hoverDistance);
            vertices[i] = transform.InverseTransformPoint(newPosition);
        }

        mesh.vertices = vertices;
        mesh.RecalculateBounds();
    }```

The video is of the script working on the sphere mesh, I just want that on the face mesh
#

or if anyone knows an assetstore asset that does this id just use that lol

wild spire
#

This script cannot work on a non sphere mesh

#

I was wondering how I could refactor this script to work on a non sphere mesh. I dont understand the math involved so if anyone knows any resources or how to it can be done that would be great help

lament bear
#

Can I use Muse Behaviour for free?

cosmic rain
thick stratus
#

Hi, im trying to detect if a nintendo switch controller is the current set gamepad within the new input system and im not exactly sure what i need the if statement to equals to as documentaion and forums havent had any answers, tbh i thought something like Gamepad.current == UnityEngine.InputSystem.NintendoSwitch.NintendoSwitchProController

wild spire
#

if you increase the X or Y scale on the sphere even a little bit the mesh wont deform properly

somber nacelle
cosmic rain
thick stratus
somber nacelle
#

what exactly did you try

thick stratus
#

nvm figured it out, i tried Gamepad.current is UnityEngine.InputSystem.NintendoSwitch.NintendoSwitchProController when instead its Gamepad.current is UnityEngine.InputSystem.Switch.SwitchProControllerHID

somber nacelle
#

make sure that your !IDE is configured so that it will autocomplete stuff like that so you don't make mistakes like that in the future

tawny elkBOT
mossy snow
wild spire
mossy snow
#

I take it the eye mesh is 3D and not a simple texture then

wild spire
#

Yes its a plane

mossy snow
#

that's two dimensional. Why wouldn't a decal work for you?

wild spire
#

Decals project onto all surfaces, I want to be able to resize and move the eyes in the character creator, and decals project on top of the hair mesh or whatever else

mossy snow
#

what RP are you using?

wild spire
#

URP

wild spire
#

Damn I was looking for this a few months ago but couldn’t find it. Thank you I’ll try that tomorrow

copper grove
#

got a question
I tried lowering the M and it worked but why did a capital there ruin my whole script

mellow sigil
#

Because you already have another script called PlayerMovement

copper grove
#

no i dont

mellow sigil
#

That's what the compiler says and it knows better than you

rigid island
copper grove
#

nope

fervent furnace
#

find a script, create a PlayerMovement field, then press it and let your ide open the PlayerMovement class

dense crow
#

how can i convert from csv file into TextAsset file in unity ?.

#

i want to attach it into an editor tool

mellow sigil
#

CSV files are already text. There's nothing to convert

quartz folio
#

and they already are one of the extensions that import as a TextAsset

dense crow
quartz folio
#

what's the file extension?

mellow sigil
#

judging by the icon that's an Excel file

dense crow
#

it is csv

#

oh it worked, thanks u guys

#

the correct one is the book1 on the left of excel file in image.

eternal dome
# wild spire Hello everyone. I have been looking into mesh deformation in unity and have gott...

looks like decal projector

New in 2021! URP (URP12) supports a Decal Projector much like HDRP has had since HDRP6!

🚨 Starting with Unity 2022.1 / URP14 Render Layers are supported! https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@14.0/manual/renderer-feature-decal.html

Many of us who aren't super comfortable writing our own shaders relied on 3rd pa...

▶ Play video
dim forge
#

hello there,
i'll be implementing a dungeon generator kind of like the one that is used in Enter the Gungeon. This means i'll have some graph structure of rooms and will have to connect rooms to one another. But i'm not sure how exactly to represent doors in these rooms to make it easy to connect them. I thought i could have every room as a prefab, with empty objects marking where the doorways are. Then, in the script, i would just line up a door to the global location of another door to connect them. Does this sound like a good way of doing it? Below is an example of the graph that represents the dungeon in Enter the Gungeon.

hexed pecan
dim forge
#

otherwise rooms are directly connected via doors

hexed pecan
#

Alright. I'd say try it and see if you run into any issues

dim forge
#

alright, thanks

dusky niche
#

How do I check if an animation has finished playing through code?

thin aurora
dusky niche
#

It has to be greater than normalized time right?

thin aurora
#

But you can try debugging these values to see if this is truly the way to check it

dusky niche
#

there's one issue

#

if (this.player.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 .IsName("WeaponSwitchDown")

#

I can't use IsName

thin aurora
#

Well not like that obviously

dusky niche
#

if (this.player.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && this.player.GetCurrentAnimatorStateInfo(0).IsName("WeaponSwitchDown") well this works

thin aurora
#

What you probably want to do is this:

if (this.player.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 > 0)

For checking if the animation is playing.

#

The value actually holds two numbers. One for the number of loops and one for the progress of the current loop

#

And in this case the fractional part (0.0-0.9) is the progress

#

So by using a modulo like this you strip the whole number and check the fraction if it's higher than zero

#

Idk how the precision works here but maybe you want to account for imprecise values

#

Try debugging this and see if this is truly what you expect

#

My initial answer was a quick Google search and all these answers actually end up being completely wrong, sorry for that

dusky niche
weary dawn
#

Using Unity 2022.3.18f1

#

And yes, i want to try making a Unity project that exports to excel

chilly surge
weary dawn
#

Is it the package name?
"NuGet’s package name is NPOI"

weary dawn
#

Found it. But what do i do with
dotnet add package NPOI --version 2.7.0-rc1

chilly surge
chilly surge
weary dawn
#

dam

chilly surge
#

You can either use an assets that integrates NuGet packages if you are going to use a ton of them, or you can simply do it by hand if you don't mind it.

weary dawn
#

how do i do it by hand?

#

You can dm me if it will take a lot of time

#

if youre ok with that

chilly surge
#

Click the "download package" button on the NuGet page of the package, extract the downloaded file, and locate the .dll file of the correct architecture, then just drag it into Unity like any other asset.

dusky niche
knotty sun
dusky niche
knotty sun
#

what? Of course you can

dusky niche
#

can I show you the code?

knotty sun
#

no need, let me show you what I think you meant but did not write

if (
(player.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1 && player.GetCurrentAnimatorStateInfo(0).IsName("WeaponSwitchDown")
 || 
{M4.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1 && M4.GetCurrentAnimatorStateInfo(0).IsName("WeaponSwitchDown")))
#

also checking for >= 1 is not a good idea > 0.99f would be better

dusky niche
#

there's a '{'

knotty sun
#

so what?

#

the important thing is you need to encapsulate the ands outside of the or

heady iris
#

Making it work for a completely arbitrary mesh is going to be a lot more work than just deforming things onto a sphere.

heady iris
jagged snow
#

If I'm only retrieving a single value based off another value is it always better to use dictionary?

    {
        switch (impactType)
        {
            case ImpactType.Physical: return _characterImpact;
            default:
                return _groundImpact;
        }
    }```
fervent furnace
#

if the range of value (one to one/many mapping) is small, using dictionary is wasting memory and increasing query time, array is better

hard viper
#

Dictionary saves time in the sense that access is O(1), mostly independent of the size of the collection. But that comes with higher overhead cost.

fervent furnace
#

array and dictionary are both hashtable or hashmap or one to one/many mapping btw

hard viper
#

isn’t array just a pointer?

#

they should be contiguous memory

heady iris
#

Arrays are contiguous, yes

fervent furnace
#

hash table is just a abstract data structure that describes "something" has O(1) delete/remove/add key-value pair

heady iris
#

a hash table is a specific kind of data structure

#

the abstract structure would be an associative array

#

(or a "map")

#

that's what I usually say

#

note that a dictionary is going to be easier to reason about and implement

#

so i'd probably just use a dictionary

#

A switch expression would also be reasonable (and easier to look at)

#
GameObject GetSpawnVfx(ImpactType impactType) => impactType switch {
  ImpactType.Physical => _characterImpact;
  ImpactType.Magical => _kablooey;
  _ => _groundImpact;
};
#

One annoyance: if you don't include the _ case, the compiler will complain that you don't handle all possible values

#

since it's perfecly legal to do ImpactType what = (ImpactType) 123456;

#

I turned off that warning, because adding a default case can wind up obscuring another problem

#

imagine I start with

public enum Stuff {
  Foo,
  Bar
}

and I write this:

stuff switch {
  Stuff.Foo => 1,
  Stuff.Bar => 2
}
#

I could silence the warning by adding _ => 0 or something

#

But if I then added a Baz value to Stuff, I could easily forget to add a case for it in that switch expression

#

because there's no warning: the _ case will handle it

#

by leaving out the _ case, I get a compiler warning if I add a new value to Stuff without updating the switch

#

I find that to be way more useful

chilly surge
#

Enums being just its backing type and thus no exhaustiveness is such an annoyance in C#.

heady iris
#

yeah

#

give me my damn algebraic datatypes already

quaint rock
#

a Dicitonary could be used for this as well

heady iris
#

C# has baby's first pattern matching

quaint rock
#

enum keys to the prefabs

heady iris
#

and you can't exhaustively reason there either!

quaint rock
#

but yeah i mostly just make the default case or _ just throw a exception

#

C# type system does not let me restrict this how i want, but its a programmer error so a exception is the way

heady iris
#

this is exhaustive, compiler!

hard viper
#

wdym by exhaustive

heady iris
#

there are no possible situations in which that switch statement doesn't match and return

hard viper
#

yes there are

quaint rock
#

null

hard viper
#

nvm it is internal

quaint rock
#

ah nvm that is check first

heady iris
#

ideally i'd just have null-aware code

#

there is no way for someone outside of my assembly to extend any of those classes, and parent isn't null

#

It's possible that the compiler just can't reason about the null check

quaint rock
#

but yeah would be nice if it was aware, since then as you added types it would compiler error where you need to add cases

heady iris
#

it persists with a case null

hard viper
#

yeah, but it’s hard to write a compiler error to explain “you need a default case, except when this explicit set of conditions are met”

heady iris
#

like..it's true, yes

chilly surge
#

I have no idea how "hard" it is, but plenty languages have it.

hard viper
#

hard to explain, not as hard to implement

heady iris
#

but silencing that warning with a default case produces a new kind of wrongness

thick terrace
#

i think it's still technically possible with various reflection black magic and/or interop with other languages to violate that check

heady iris
#

i would simply not do that thinksmart

quaint rock
#

to be fair saying cause reflection is a bit of a cop out

#

like you can break almost anything with it

thick terrace
#

most unity programmers never would, but the C# world is larger and full of sickos, so it's a language restriction 😛

heady iris
#

Some kind of middle-ground would be acceptable

quaint rock
#

thats like complaining that Rust or Go can leak memory because of unsafe

heady iris
#

where it warns you if you have a default case that covers a situation the compiler thinks is possible

#

so not a default case

#

a wtf case

quaint rock
#

i guess other cases, which you did cover with internal i know

#

would be types from other assemblies extending it

thick terrace
#

actually you did cover the base type so idk, even with reflection you wouldn't be able to slip one past it

heady iris
#

This is probably necessary for some truly godforsaken COM machinery

quaint rock
#

ugh COM

heady iris
#

ultimately, it's impossible to have a type system in which:

  • every valid program is accepted
  • every invalid program is rejected
#

thus the compromises are made

quaint rock
#

used to have a pile of COM+ code for syncing photoshop selections with Maya selections based on UV layout

quaint rock
#

it was ugly messy stuff

#

was a really neat feature to have though

heady iris
#

yeah, and that demonic pact probably sounded really sweet when you signed it

hard viper
#

is there a way to make an animated tile with a physics shape, the physics shape is the same each frame, the tilemap with a composite collider, and avoid refreshing the composite collider when the animated tile animates?

quaint rock
heady iris
#

no

#

i can't imagine it's pleasant

#

the most i've done is write scripts for Illustrator

heady iris
quaint rock
#

so, because not everything is acceisable via it i needed, i had to record actions, save them to a binary blob, then tell PS to execute that over the com interface

#

also had a few things break since PS actions often break if you change your UI layout

#

PS is such a freaking mess of a program

hard viper
#

animated tiles are kind of awkard to reset to a global timer rn. there’s just a lot of little quirks

cinder spruce
#

I have a series of card all sharing the same model. ut each card has itts own set of textures.
Is there a way to have a prefab use the texture in the same folder, or do i need to open each card prefab and assign the texture to it ?

#

I could do it on start or awake, but this sounds like extra operations that could be done before the project is built

hard viper
#

oh animated tiles have an update physics flag. all good

hard viper
#

or a monobehaviour that does the same thing, but SO will be simpler if you need it on multiple scenes

cinder spruce
heady iris
#

Vaguely

#

But I'd think having dozens and dozens of duplicate prefab assets woulds be worse than just having one prefab that you customize.

cinder spruce
# heady iris Vaguely

I'm not sure. They wont be duplicate they will be prefab variantes. They basically only save the overrides, aka the texture changed.

heady iris
#

dozens of prefab variants also sounds miserble

#

You should create prefab variants when you need to add new things and make changes by hand

#

putting a new texture on a card isn't something you need to do by hand

novel raven
#

whats the best way to catch all keyboard inputs (primarily alphanumerical), i was using Input.inputString but that seemed to drop inputs if i pressed buttons fast, im looking at the new input system but cant find a way to query all inputs

steady valley
#

Hey, I have a quite big problem with my unity project, and would really appreciate help please.
Due to some git issues, I came back to some old versions of the project, and now I have a lot of compilation error with the project, that I have undepending of the git commit version.
I have a lot of plugins in a Standard Assets folder and I have referencing issues between Runtime and Editor scripts of 2 plugins. Also I think my unity assets were broken and had to reinstall them
Looking at the documentation (https://docs.unity3d.com/Manual/ScriptCompileOrderFolders.html), it says editor versions should always be compiled after, but all the errors I have are in editor scripts, and all the errors are about not finding the runtime class/namespace of the package.
But, I have no error in any runtime script ? Why is this appening ?

Assets\Test\ProceduralTerrainPainter\Editor\PropertyDrawers.cs(108,38): error CS0246: The type or namespace name 'Attributes' could not be found (are you missing a using directive or an assembly reference?)

I'm on unity 2023.3.0b9, didn't change version recently

#

Posting on forums is now my last options UnityChanThink

heady iris
#

Are you using assembly definitions?

steady valley
#

I don't and doesn't really know how it works, could a package use it in my project ?

heady iris
#

asmdefs group code together into compilation units, and you have to explicitly define which assemblies can use which other assemblies

steady valley
#

Okay thanks I'll read the documentation about that. Maybe there is some missing file unreferenced by git that were helping with that

#

Just found that assembly definition of one plugin have null value

#

That's probably the issue so

leaden ice
#

You should have:

  • Assets
  • Packages
  • ProjectSettings
steady valley
#

No it isn't, isn't it regenerated on first opening ?

leaden ice
#

no

#

it's part of the project

#

and needs to be included in VCS

#

The Library folder is the ephemeral one

#

Packages contains the package manifest and any embedded packages, both of which are essential parts of the project.

steady valley
#

Oh ok thanks

#

It didn't fixed the none assembly definition references problem but will surely help with git thanks

#

Manually adding the reference fixed it, thanks a lot!!

arctic plume
#

Is it possible to get the script of a gameobject from a child of that gameobject?

mellow sigil
#

transform.parent is a reference to the parent object

steady valley
heady iris
#

I am moving an object along a Spline. I need to give it a rotation offset. I see that I can attach float4 data to the spline and then evaluate it. The Evaluate method on SplineData requires an interpolator. https://docs.unity3d.com/Packages/com.unity.splines@0.1/api/UnityEngine.Splines.SplineData-1.html#UnityEngine_Splines_SplineData_1_Evaluate__2___0_System_Single___1_

I also see there's this handy SlerpQuaternion interpolator https://docs.unity3d.com/Packages/com.unity.splines@1.0/api/UnityEngine.Splines.Interpolators.SlerpQuaternion.html

However, this is float4 data, not Quaternion data, so the interpolator is incompatible.

Is there something I'm missing here that'd let me use SlerpQuaternion?

#

I suppose I can just write an interpolator that takes a float4 representation of two quaternions and does the slerp

#

but it seems weird for a SlerpQuaternion to exist without it being directly usable as an interpolator!

nova moon
#

Does anyone know how you would go about loading in a model that was not initially in the build of a project? I'm attempting to stream line an issue we have at work and would like to be able to create a simple exe with a free fly camera and a config file where the user can put the file name and/or location in to the config file, and then it will load the fbx from that location so that testing can easily view the model for any issues before it gets to the developers hands. I'm just not sure how to do that short of loading the model into unity and creating asset bundles which at that point, the developers might as well just review the model themselves.

heady iris
#

Loading a model file at runtime is different from loading an asset bundle at runtime, mind you

#

The former requires you to actually parse that model into something Unity understands

#

I do believe there are runtime fbx importers available.

nova moon
#

I was having a difficult time finding importers that are used to import into a built project. Everything I found looked like it was for importing into the editor.

heady iris
#

you might have an easier time using GLTF

#

there's a handy package already available

arctic plume
arctic plume
thick terrace
heady iris
#

you'd still need to turn it into a Mesh though

nova moon
#

I'll look into both of these options! Thanks @heady iris and @thick terrace !

arctic plume
#

Can you not reference subchildren from a parent GameObject?

heady iris
#

You can also reference whatever you want within a prefab.

arctic plume
#

But I have a Ready Player Me avatar and I can't seem to use transform.Find to get one of it's subchildren?

I even did a Debug print loop like this:

        foreach (Transform child in currentSpeaker.transform)
        {
            Debug.Log("Child: " + child);
        }

And for some reason it only prints out the DIRECT children?

thick terrace
#

that is only looping over direct children yup

#

Find should work though, but you have to include the full path IIRC

knotty sun
arctic plume
arctic plume
thick terrace
#

i don't think so, just every child beneath the transform you're searching in, so if it's a grandchild it'd be like Find("Child/GrandChild")

arctic plume
#

Ok I'll try that, thank you

#

That did the trick, thank you very much!

warm kraken
#

how do i change this default collider shape which comes with the sprite? this is and image component.

leaden ice
#

As for the sprite physics shape that's in the sprite editor

warm kraken
#

Yep. The default sprite physics shape is a quad. I changed it in sprite editor and it still shows and reacts as a quad. Am i missing anything?

warm kraken
#

Im using "OnPointerEnter" which doesnt need any colliders to detect the image when mouse is over it. But the default image collider(or whatever it is) shape is quad as you can see in my previous message. How can i change that shape to whatever shape i want?

#

here's the object and its components (sorry for spamming)

golden glade
#

Is it not possible to make a method show?
The class itself is partial, I've tried moving it into the original file and out of the generated partial class, no luck.

The method itself is

[Serializable]
public enum SoundType
{
    EMOTE_JOSHUA_MAN_PAIN_HURT_GRUNT_BIG_03 = 0,
    FAIL_3A                                 = 1,
    SUCCESS_2A                              = 2,
    SW001_8BITGAMES017_EXPLOSION            = 3,
    CLICK_03                                = 4,
}

public partial class SoundManager : MonoBehaviour
{
    /// <summary>
    /// Play a sound by type
    /// </summary>
    /// <param name="type">Type of sound</param>
    public void Play(SoundType type)
    {
        _instance.Play((int)type);
    }
}
#

And SoundType is auto-generated but I will post that too.

#

I've tried restarting Unity too but no luck either

#

does Unity inspector not like partial classes?

#

Works if the argument type is an int but not an enum.

knotty sun
#

yep, events don't work with enums

thick terrace
#

iirc that's because of the way it's serialized under the hood

golden glade
#

Weird, because on the forum they show exactly that.

#

Do you know any other way of making it work? Like a custom drawer?

thick terrace
#

what they're showing there doesn't match what you're trying to do, theirs is just a public field

golden glade
thick terrace
#

i think what they're actually suggesting is make a new MonoBehaviour with that property on it, and use that as the argument to your method

#

since any UnityEngine.Object should be ok as a parameter

golden glade
#

Thought I could make this system zero-code or additional components .. Maybe not.

thick terrace
#

i think the other way around it would be a separate script with a different type of UnityEvent with the correct type parameter, but it's an additional script either way

static matrix
#

how can I get which clip an animator is playing?

golden glade
#

Dream's dead I guess unless I somehow magically create a custom event class and an inspector for it

rigid island
static matrix
#

alright

golden glade
#

What are you trying to achieve?

static matrix
#

and I presume the base layer is 0 correct?

golden glade
#

Most likely it is in what order these are

rigid island
golden glade
#

if you do not have any extra layers then yes, 0 is correct.

vale bridge
#

Is there a way to get a component whose upper class is for example "Weapon"?

For reference I'm triyng to pull attributes like damage and trigger the weapon behaviors via an Aim script that knows nothing but the base class methods. For example if I got the reference I would call "obj.Fire()" where every class inheriting Weapon would have to implement that method; I just need the specific script that inherits this on a child object

heady iris
#

You can use a parent type with GetComponent, yes.

#

You can also serialize a reference to a parent type.

vale bridge
#

Is that how it works?

heady iris
#

All of the components you've made, at least

heady iris
#

GetComponent<Behaviour>() or GetComponent<Component>() would be even more broad

vale bridge
heady iris
#

Behaviour covers many built-in components that can be enabled and disabled

leaden ice
#

Also note GetComponent vs GetComponents

vale bridge
#

I did not know there was a difference

heady iris
#

but there are some other kinds of components too

#

Renderers, notably

vale bridge
vale bridge
heady iris
#

I just noticed that Unity is producing a warning whilst burst-compiling some code

#
[BurstCompile]
static class NoiseMethods
{
    [BurstCompile]
    public static float Noise(float t, in float2 vec, in float2 offset)
    {
        return noise.snoise(vec * t + offset);
    }
}

The warning states that compilation was requested for this, but that it's not a known Burst entry-point

#

The Burst inspector shows native code compiled from this method, so it seems like it's still working..?

#

I can't get it to re-appear after modifying my code now. I'm not sure exactly when it shows the warning

static matrix
#

tf is a burst

leaden ice
#

basically the special compiler for DOTS

static matrix
#

tf is a dots

leaden ice
heady iris
signal moon
#

Hi, im using a code found online, about good hand positioning in card game. It seems like i set everything like original autor did yet i have few problems, mainly with cards trying to leave the canvas but being blocked, and a script not reading position (those 2 are related). I have following errors: NullReferenceException: Object reference not set to an instance of an object CardWrapper.SetAnchor (UnityEngine.Vector2 min, UnityEngine.Vector2 max) (at Assets/Scripts/Cards/Card Aligment/CardWrapper.cs:106) CardContainer.SetCardsAnchor () (at Assets/Scripts/Cards/Card Aligment/CardContainer.cs:207) CardContainer.InitCards () (at Assets/Scripts/Cards/Card Aligment/CardContainer.cs:54) CardContainer.Start () (at Assets/Scripts/Cards/Card Aligment/CardContainer.cs:49)

and

CardWrapper.get_width () (at Assets/Scripts/Cards/Card Aligment/CardWrapper.cs:28)
CardContainer+<>c.<SetCardsPosition>b__23_0 (CardWrapper card) (at Assets/Scripts/Cards/Card Aligment/CardContainer.cs:157)
System.Linq.Enumerable.Sum[TSource] (System.Collections.Generic.IEnumerable`1[T] source, System.Func`2[T,TResult] selector) (at <523a924aba464755b1747653b71e5189>:0)
CardContainer.SetCardsPosition () (at Assets/Scripts/Cards/Card Aligment/CardContainer.cs:157)
CardContainer.UpdateCards () (at Assets/Scripts/Cards/Card Aligment/CardContainer.cs:125)
CardContainer.Update () (at Assets/Scripts/Cards/Card Aligment/CardContainer.cs:80)```
heady iris
#

It only works with a limited subset of C#

#

"Bursted" code is completely unmanaged.

#

You aren't running stuff in the managed C# runtime

heady iris
signal moon
heady iris
signal moon
heady iris
#

Okay, but have you done any debugging?

heady iris
signal moon
#

there is only 1 line in Awake method private void Awake() { rectTransform = GetComponent<RectTransform>(); } yet every object has rect transform.

clear oriole
#

I did eventually figure it out, its in the camera Data is where you have to set it

lean sail
#

It looks like a different method entirely is throwing a null error by the stack trace