#archived-code-general

1 messages · Page 250 of 1

latent latch
#

otherwise probably better off on an OpenGL server

simple mountain
#

you can use unity's mesh library externaly?

latent latch
#

eh, I don't believe so

#

It's just an API on top of other APIs

simple mountain
#

yeah no, my issue is related to binding textures to image units, how does that work in unity?

latent latch
#

Are you talking about shaders specifically?

#

Most done through HLSL

#

which is kinda like GLSL, though Unity's got a lot of their own methods in place

simple mountain
#

yes how do you write to a texture in hlsl?

latent latch
#

that's for built-in though

#

newer Pipeline stuff you'll need to dig around

simple mountain
#

thanks looks pretty cool

latent latch
#

and if you know how it works conceptionally then you've also have ShaderGraph which is more node based

simple mountain
#

hlsl shaders look like like json

warm kraken
#

hey guys. i used unity's integrated version control in one of my projects and now all of my projects have these green icons telling me to "check-in" the changes. is it possible to disable it in some projects and enable it in others? also i have a lot of archived projects in unity cloud. is there a way to delete those? (second picture)

simple egret
lunar acorn
#

I moved the scripts of my game into a folder called scripts. I didnt change a single word in any of them. Now every single script with an Action is telling me it needs to be of type delegate. All namespaces are in folders with the coordinating name. I tried moving them all back to the assets folder and the error wont go. Is something wrong with the Assembly Definitions or something?

simple egret
#

Did you name your own class Action? It might be picking up that one instead of System.Action as it's "farther" compared to the stuff you put in the global namespace

lunar acorn
#

Omg.................................... Thats LITERALLY what happened. THANK YOU!

simple egret
#

What you can do is try to navigate to the definition of that class, if you ever have these kinds of errors in the future. Ctrl+Click the Action for example, and it'll take you to where it's declared. Ensure it's where you expect!

lunar acorn
#

Wow! That is great advice. I kept clicking the definition for the different delegates themselves but not Action since it wasnt underlined. I should always check the class first!

dense rock
#

How do I get a list of scriptable objects from a path? I'm trying everythings but I can't get it to work...

quartz folio
#

For what reason? Is this for an editor tool?

dense rock
#

yes

quartz folio
hard viper
#

It's supposed to be in the namespace UnityEditor.SettingsManagement;

quartz folio
hard viper
#

no

#

I can get the package by adding a different package that adds it as a dependency. But right now i'm trying to edit that package, because it has a typo

quartz folio
#

Or just add it via name

hard viper
#

wdym?

#

how would I know the name

quartz folio
hard viper
#

you're too smart

#

it's bullshit that it was invisible, but you helped a lot

stark elk
#

umm guys, i just installed unity 2019.4 on windows 7 and its not opening What should i do?

somber nacelle
#

this is a code channel

dense rock
#

Hey, I'm trying to have multiple SOs inheriting from a generic SO, each storing a Value of the type. When I want to have a field of the base SO class and create it as one of its inheriting classes, that doesn't work because I need to specify the generic in the field declaration... What do I do?

private ValueBase value; // needs generic like ValueBase<int>

if(...) value = new IntValue();
else if(...) value = new BoolValue(); // doesn't work if i declare value as type ValueBase<int>

value.ValueName = "someName";

I tried making the ValueBase<T> implement an interface, but when I declare the value as type of that interface, it doesn't let me access the fields of value anymore, as the interface doesn't have those fields...

fervent furnace
#

You want one value can hold different types?

hard viper
dense rock
#

but then I can't access the fields of type T in it, can I?

hard viper
#

expample:
public abstract class FixedSpawnpointBase {}
public abstract class FixedSpawnpointBase<T> : FixedSpawnpointBase {}
public class FixedSpawnpointSingle : FixedSpawnpointBase<TilePlacementSingle> {}
public class FixedSpawnpointLine : FixedSpawnpointBase<TilePlacementLine> {}

dense rock
#

i need to do that tho :/

hard viper
#

well how are you going to do that without knowing what type it is

dense rock
#

I wanted a switch statement to set it as the new type

hard viper
#

that is bad. don't do that

dense rock
#
switch (valueType)
{
    case ValueTypes.Int:
        GlobalIntValue intValue = new GlobalIntValue();
        break;
}
value.Name = "";
#

the classes are Scriptable Objects and I want to create one in the editor whilst deciding its type there

hard viper
#

why are they generic on value types that you don't define

fervent furnace
#

You can use a enum and pointer to have a fixed size allocations first, but finally you will find that you are reimplementing a compiler

hard viper
#

when I do this sort of thing, the generic argument is one of my classes, so I slap an interface on that shit

dense rock
#

public abstract class GlobalValueBase<T> : ScriptableObject
{
    public string Name;
    public T Value;
}
public class GlobalIntValue : GlobalValueBase<int>
{

}
#

thats what I was doing

#

if(valueType == ValueType.Int) value = new IntValue();

#

and then access it's parameters

hard viper
#

what are these different types for T

dense rock
#

string, int, bool, float, later maybe classes too

hard viper
#

ok, that makes zero sense to try to store on a single variable

fervent furnace
#

See, reimplementing compiler

dense rock
#

well shit

hard viper
#

yeah dude. what you are trying to do is just dumb

#

there is a smarter way to structure your code, that doesn't involve any of this

dense rock
#

thats what I'm doing in the editor btw

#

I don't know how else to achieve my goal

hard viper
#

..... no

#

you need to ask yourself WHY are you trying to store the same one variable, but with so many types that have nothing to do with each other

dense rock
#

I mean, there's a button below that then creates the ScriptableObject of the type

hard viper
#

ok

#

WHY do you need a base SO where all these random types are on the same variable

#

WHY

dense rock
hard viper
#

ok. make them different variables

#

problem solved

hard viper
#

make a generic data entry

dense rock
#

what

#

example?

#

List<T> mylist;?

hard viper
#

if you want to store all of these, then I would make a separate little container class that does different things depending on its contents

#

I just don't see how you can actually use all of this in a way that makes sense.

dense rock
hard viper
#

I'm working on a save data thing with a similar thing, but the way that works is that my code just acts on an ISaveData interface to call .Load(), and the inner logic takes care of the rest

dense rock
#

I want to have a ton of SOs each storing a value. Also they should be shown all together in a list.

hard viper
#

that's wonderful

#

just make it a different variable

dense rock
hard viper
#

they don't need to all be one variable that can take on every type

hard viper
dense rock
#

u mean like

switch (valueType)
{
    case ValueTypes.Int:
        GlobalIntValue intValue = new GlobalIntValue();
        intValue.Name = valueName;
        intValue.Category = category;
        AssetDatabase.CreateAsset(intValue, SO_PATH + GLOBAL_VALUES + "/" + valueName + ".asset");
        AssetDatabase.SaveAssets();
        break;

    case ValueTypes.Bool:
        GlobalBoolValue boolValue = new GlobalBoolValue();
        boolValue.Name = valueName;
        boolValue.Category = category;
        AssetDatabase.CreateAsset(boolValue, SO_PATH + GLOBAL_VALUES + "/" + valueName + ".asset");
        AssetDatabase.SaveAssets();
        break;

    case ValueTypes.Float:
        GlobalFloatValue floatValue = new GlobalFloatValue();
        floatValue.Name = valueName;
        floatValue.Category = category;
        AssetDatabase.CreateAsset(floatValue, SO_PATH + GLOBAL_VALUES + "/" + valueName + ".asset");
        AssetDatabase.SaveAssets();
        break;

    case ValueTypes.String:
        GlobalStringValue stringValue = new GlobalStringValue();
        stringValue.Name = valueName;
        stringValue.Category = category;
        AssetDatabase.CreateAsset(stringValue, SO_PATH + GLOBAL_VALUES + "/" + valueName + ".asset");
        AssetDatabase.SaveAssets();
        break;

}
hard viper
#
    public interface ISaveData {
        /// <summary>Parse the information in this instance, and apply it to the game world..</summary>
        public void Load();
    }
    /// <summary>Interface for something that makes ISaveData on request. </summary>
    public interface IDataSaver<out TSaveData> where TSaveData : ISaveData {
        /// <summary>Create a save data based on the current state of the world.</summary>
        public TSaveData MakeSave();
        /// <summary>When there is no data, do this to the level when we load.</summary>
        public void LoadDefault();
    }```
hard viper
dense rock
#

true, thats what I'm trying to avoid here xD

hard viper
#

just make different types

#

as in, not the same

#

give it an interface

#

split it up

dense rock
#

as in, not inherit from the generic base class?

hard viper
#

yes. stop with the generics

#

you're going insane

dense rock
#

true

hard viper
#

this is cancer

#

stop it

dense rock
#

that's what the generics did to me

#

I'm trying to write some expandable code here, but that shit fs me over

#

how can I then tho store them in one list?

#

do I just make the list of type object or smth?

hard viper
#

make an interface. treat them differently, because they are clearly not the same

fervent furnace
#

You need to do this if you want to store different type and dynamic cast them (ie you need something to runtime determine their type), and dont that if you can

dense rock
hard viper
#

I just don't understand how a class can hold a string vs int vs float and "maybe some other types later", and that these classes are all so similar that they should be treated as one generic

dense rock
#

you're probably right

hard viper
#

they are too different. so treat them differently

dense rock
#

how do I approach this?

public interface IGlobalValue
{
    public object Value { get; set; }
}
hard viper
#

you could successfully store the value of a different type, sure. But then how the hell is the rest of your code going to interact with that class without having its own giant switch case nonsense again.... every time it wants to do anything with the contents

hard viper
#

because my Load() function has no type-specific anything, so its interface does not either

dense rock
#

I see

fervent furnace
#

If you really want to store dynamic type, look at any dynamic type language interpreter eg python to learn ( i didnt read cpython source code btw)

dense rock
#

so I will make my interface without any contents I guess?

hard viper
#

then the objects that create savedata ARE generic, with an out T, so they can just out an object that implements a given interface

dense rock
#

if I use an interface I wont have any way of accessing their fields tho too, right?

#

and then I need to resort to giant switch statement again...

celest iron
#

I to recommend the "new" way to do switches, which is way less verbose.

cosmic rain
#

I don't know the whole context. Only seen the switch block code that you shared, but it can be compressed down to one line probably. With the implementation for each type defined within the type.

dense rock
celest iron
#

True. Too much repeated code.

cosmic rain
dense rock
#

so I add a method for creating the scriptable object to the interface and implement that in each of the inheriting classes?

dense rock
celest iron
#

On the link I sent

dense rock
#

oh sry

celest iron
#

There is a better one

#

You can differentiate both switches knowing that the "regular" one is a switch statement, while the new is a switch expression.

dense rock
#

i see, looks really interesting

cosmic rain
#

You can also have a base class that does the repetitive work.

dense rock
#

tldr;
I want SOs holding a value of different types, so I can store all global values for my game. I'm having trouble structuring the code so I can compare SOs values in the editor to form conditions and also want them to be all in one list, so I can have a good overview in the inspector.

celest iron
#

I would do something like

#

Then

#

Obviously something better than that, but you get the picture

dense rock
#

what's the "where T : struct" for?

celest iron
#

Oh just for this example

#

It's good practice to limit your generics

dense rock
#

i see :)

celest iron
#

In this case I only accept structs

fervent furnace
#

He wants his generic to be all types (class and struct)

celest iron
#

Then don't use where

silk dust
#

im working on an inventory system in unity, which right now is being save in a Dictionary
//int is the index in the hotbar
Dictionary<int, ItemScrOBJ>

My problem is that I want to added an item count, as a separate int var. What would be a good way to implement this new var. I was thinking
Dictionary<int, Dictionary<ItemScrOBJ, int>>
but I'm not sure if its a good implementation

cosmic rain
rigid island
#

Any ideas why my Grid would be off like this ?

#
void Update()
    {
        mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        mousePosGrid = theGid.WorldToCell(mousePos);
    }

    private void OnDrawGizmos()
    {
        if (!Application.isPlaying) return;

        Gizmos.color = Color.cyan;
        Gizmos.DrawSphere(mousePosGrid, 0.12f);
        Gizmos.color = Color.red;
        Gizmos.DrawSphere(mousePos, 0.12f);

        Handles.color = Color.yellow;
        Handles.Label(mousePos, mousePos.ToString());

    }```
silk dust
rigid island
silk dust
#

it might

rigid island
#

not sure if I should ceil or round

silk dust
#

ceil would put it in the top left corner

silk dust
rigid island
# silk dust round

yeah I just ended up using mousePosGrid = Vector3Int.RoundToInt(mousePos);

rigid island
silk dust
#

I recommend you change from free aspect to a fixed aspect ration in unity when working with any UI. Problems like this tend to rise when you dont

silk dust
leaden ice
#

Red x means it has negative width or height

uncut pebble
#

none of the ebook links work in the pinned message for me - do they need updated?

vagrant blade
#

They work for me?

uncut pebble
#

Hm - have tried two different browsers as well.

#

Odd.

#

Question, though - is it possible to take a screenshot of a canvas consistently even when the size of the screen may change? The ScreenshotCapture class doesn't seem to work for it

simple ruin
#

@quartz folio here is the singleton in question. It manages data that must persist between scenes

quartz folio
#

You should link to large codeblocks in future; but yes, that looks fine, it destroys itself if there's another one already

simple ruin
#

My apologies, i'll keep that in mind for the future

vital oracle
#

I'm having trouble figuring out how to do accomplish this. Any ideas welcome.

  • Have multiple small islands, around 10x10 tiles max
  • Each island has tiles where buildings can be placed and some tiles where they cannot be placed
  • Each island is a separate game object. I have a variety of them and will spawn them randomly on the map.

Everything is grid based, 16x16 tiles/sprites. Once I figure out how to properly store the data for each island I can then move onto working on placing the buildings on the buildable grid locations.

fervent furnace
#

I think you don’t need gameobject per island, just load the layout then put it in tilemap or whatever you like

earnest gazelle
#

Why do I see a warning in my compute shader when defining a field with name point?

struct WaterSourceData
{
    int3 point; //here
    float amount;
};

Declaration does not declare anything
'point' specifier is ignored when there are no declarators

thin aurora
# celest iron It's good practice to limit your generics

Not even that, applying these rules will expose various methods and properties that would exist in the type, now that it is restricted. You are very limited to what a Genetic can do if you do not apply any restrictions on them.
For example, restrict the generic to implement a certain interface, and you will have access to the implemented methods and properties from that interface.

late lion
bronze crystal
#

what libraries are good for game building withc++

west lotus
#

How is this a unity related question ?

simple mountain
cosmic rain
west lotus
#

:gasp: he who should not be named

craggy veldt
#

sfml has a official c# binding at least, unlike sdl

#

oh forgot this is unity server 😅

#

why you want to do that?

knotty sun
#

ban comments? why on earth would you want to do that?

craggy veldt
#

wat?

#

clean code has nothing todo with code comments

quartz folio
#

This is a load of shit

cosmic rain
#

There are cases where comments are not needed and cases where they are very helpful. You can't really say "comments are not needed(entirely)"

#

Besides, if you have time to worry about that, you should spend it on development

#

Then you haven't had to deal with complex systems and big projects. From my experience I would pay money for there to be comments sometimes.

quartz folio
#

Comments shouldn't describe the code literally, but what the idea was behind a particular implementation, or what sources were referenced, or what to watch out for when maintaining it

craggy veldt
#

again dude, code comments has nothing todo with clean code

cosmic rain
#

Anyways, that should make it clear that no one hear knows how to disable them, since we never had a need in it.😬

#

Did you ever work in a team or a codebase that someone else wrote?

craggy veldt
#

Many? mention the first 5 at least?

cosmic rain
#

Well, great then. If you don't need comments just don't write them.

quartz folio
#

We don't need to go into bragging

#

If you want an answer go ask the C# Discord

#

Where they will probably also laugh

#

!cs

tawny elkBOT
sleek bough
#

It's not a magical fairy, you don't need to believe in it. It's basic core practice.

#

@hot quest Once again you were pointed where to take it already.

latent latch
#

anytime I think of commentless code I think back at my math professors writing computer algs without clarifying any variables and just expecting me to understand what everything is

#

just math professors and pseudo code in general

sleek bough
#

For the last time. Stop posting off-topic.

quartz folio
#

Move on, we don't need or want this discussion

quartz folio
#

!code

tawny elkBOT
spring basin
#

there's something weird happening

#

I implemented the navmesh movement ai from unity in ecs

#

it works perfectly fine on the editor

#

when i make an android build or a windows build for that matter, it travels in a straight and gets blocked by obstacles

#

im guessing it fails to load the navmesh baked data on builds

#

is there anything specific that has be done for prebaked navmeshes to work on builds?

thin aurora
#

By sitting down with your team and discussing the use of comments in your project. Not everything can be handled with just well written code, comments exist to explain the harder to understand features.

quaint rock
#

also banning comments would be a massive mistake

thin aurora
#

Don't want to go off-topic again, but even simple comments very often can indicate what a block of code does, without needing to spend time figuring it out yourself

quaint rock
#

the code only says what is going on, it does not say why

fervent furnace
#

you can write a simple program (leetcode medium level) to process your code......btw the discussion was end

thin aurora
#

Just wanted to vent my opinion since I severely disagreed with the take, but I was too late 🙂

swift falcon
#
//Prints Hello
Console.WriteLine("Hello");
#

Banned

#

in other topics AI have gotten better at commenting code

nimble cairn
#

Does using Vector2.zero increase GC at all? Am I better off having:

Vector2 zero = new(0, 0);

void Update() {
    if (randomVector != zero) foo();
}

OR

void Update() {
    if (randomVector != Vector2.zero) foo();
}
latent latch
#

I doubt it matters but Vector.zero looks cooler

nimble cairn
#

xD

swift falcon
#

no gc pressure at all structs allocated on stack

nimble cairn
#

Is there any overhead in the Vector2.zero call? If so, having a predefined private variable will eliminate this overhead.

swift falcon
#

no need to create your own var though

#

Just use Vector2.zero

#

Vector2.zero uses default(Vector2)

latent latch
#

I've read that structs do generate some amount of garbo or something in the passed, but even if it doesn't I'm not changing up my unmanaged structs ;p (c# specifically)

fervent furnace
#

probably fetching a static variable in somewhere may require little time, but not the reason that using extra 8 bytes to store it (one instance =8 bytes, many instance=many 8 bytes)

nimble cairn
#

Good to know!!

#

Thanks again 🙂

swift falcon
#

value types as far as i know like structs are stored on stack

#

GC only deals with heap

latent latch
#

He's got a bunch of interesting stuff for microperformances

nimble cairn
#

Love your work

latent latch
#

and why you should use pointers

#

specifically for events

swift falcon
#

oh i use Pointer structs too

#

Cause value types are pass by value

latent latch
#

events actually do generate a lot of garbo

swift falcon
#

Notice that neither “normal” non-generic struct creates any bytes in the “GC Alloc” column. The generic struct also has zero bytes in the “GC Alloc” column, but only when using the default constructor that takes no parameters. When using the non-default constructor that does take parameters, the generic struct suddenly starts allocating 32 bytes of garbage.

#

interesting

latent latch
#

Ah, ok right now I remember this

swift falcon
#

Most people do this tbf

#

Also really old post 😄

#

I wonder if theres been any updates

latent latch
#

Yeah, it is old but I came across this website because I was getting microstutters with subscribing

swift falcon
#

unity profiler is pretty nice for this

#

I think its got gc alloc somewhere in the chart

latent latch
#

Which is what I've changed a lot of my subscription models to ^

swift falcon
#

ty

#

Im also using unity events

#

I can see what this person is doing

#

public void Dispatch(int enemyId, Vector3 location)

#

Removing object completely

#

And using value types

#

If you're recieving a huge amount of events in a short time then this should be good

latent latch
#

Basically, I've a bunch of abilities and stuff that listen to statistical changes

#

and then I do a lot of caching

#

*changing stats would prompt all abilities subscribed to update accordingly so I could cache their formulations without doing it throughout the usage, but more importantly would be my enemies spawning and subscribing to game related events when dequeued from my pool.

swift falcon
#

Not really much choice i got tbf but thankfully gc isn't a issue for me rn

latent latch
#

Yeah, if it aint a problem, dont fix it lol

fervent furnace
#

just took a look on new publisher-subscriber model
just having a hard-coded way to call manager first then probably call all the instances under manager

public static list<ABC> ABCs;
public static void SomeoneCallsOurs(args){
  foreach(ABC a in ABCs){a.Listen(args)}
}
ABC(){
  ABCs.Add(this);
}
public void Listen(args){}
```i do this if no "manager" is needed
gleaming gale
#

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

public class playermovement : MonoBehaviour
{
// Adjust the speed to your liking
public float movementSpeed = 5f;
public float jumpForce = 5f;

// Reference to the Rigidbody component
private Rigidbody rb;
private bool isGrounded;

void Start()
{
    // Get the Rigidbody component once at the start
    rb = GetComponent<Rigidbody>();
    rb.freezeRotation = true; // Freeze rotation to prevent unwanted physics interactions
    isGrounded = true; // Assume the player is initially grounded
}

// Update is called once per frame
void Update()
{
    // Move up
    if (Input.GetKey("w"))
    {
        rb.velocity = new Vector3(0, 0, movementSpeed);
    }
    else if (Input.GetKey("s"))
    {
        rb.velocity = new Vector3(0, 0, -movementSpeed);
    }
    else if (Input.GetKey("d"))
    {
        rb.velocity = new Vector3(movementSpeed, 0, 0);
    }
    else if (Input.GetKey("a"))
    {
        rb.velocity = new Vector3(-movementSpeed, 0, 0);
    }
    else
    {
        // If no movement keys are pressed, stop the movement
        rb.velocity = new Vector3(0, rb.velocity.y, 0);
    }

    // Jump with space key if grounded
    if (Input.GetKeyDown("space") && isGrounded)
    {
        rb.velocity = new Vector3(0, jumpForce, 0);
        isGrounded = false; // Set to false when jumping
    }
}

// OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider
void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = true; // Set to true when landing on the ground
    }
}

}

#

do you know whats wrong?

#

objects supposed not to be able to jump until it hits the ground

#

ground has a collider

hard viper
#

@indigo hound hey. I upgraded my ClassTypeReferences to the fork that you are using, and noticed the UI breaks if there are 10+ types included in the single search. At 10 types, it changes to a search bar that references a broken Unity component. I fixed this by going to ProjectSettings > Packages > TypeReferences > Minimum searchbar item count.
Change this from 10 to 9999

leaden ice
indigo hound
placid summit
#

Hi is there a downside to exposing auto properties to the inspector with [field: SerializeField]? like for public Vector3 TargetPos { get; set; } ? I know the backing field has odd syntax but not sure it matters

vagrant blade
#

Not really, unless you consider cluttering your inspector as a downside

placid summit
#

cluttering inspector? Well obviously I will only expose where required

#

just quicker than exposing a private field and then adding a property

heady iris
# placid summit Hi is there a downside to exposing auto properties to the inspector with [field:...

I ran into a problem with this recently. I originally had an interface that called for:

public LocalizedString Label { get; }

Each implementor had:

[field : SerializeField]
public LocalizedString Label { get; }

I then switched to an abstract class that implemented the interface, and had:

public abstract LocalizedString Label { get; }

And thus I switched the children to have:

[field : SerializeField]
public override LocalizedString Label { get; }

At this point, Label stopped showing up in the inspector.

placid summit
#

because you need set also for it to show up, that is why

faint otter
#

dont believe you need [Field :]?

#

just the [SerializeField]?

heady iris
#

You need to explicitly target the backing field.

latent latch
#

The only downside is when you need to work on the backing field then it gets a little messy

#

via attributes and such which you need to target directly

placid summit
#

oh no not true...

#

you need field: is property

#

*if property to say backing field

heady iris
#

If you look at the serialized data, you'll see something like this

#

<Label>k__BackingField:

faint otter
#

So i want to have a changing amount of rigidbodies in 2d box, i want when 2 rigidbodies with the same tag to report to a controller script that will then do something with these collisions. how would i do this? i would assume events but there will be can i add more and less events whenever i want?

heady iris
#

Oh, that's exactly what the problem was.

placid summit
heady iris
#

I got rid of it when I switched to overriding an abstract property because I didn't include that in the abstract property.

#

I just decided to switch to an explicit field anyway (it was easy to migrate with [FormerlySerializedAs]

#

followed by forcing the serialization of every asset

placid summit
#

so I would not mind an explicit field but I would need an IDE tool to make it quick for me! I need speed and non-auto properties take time and more clutter!

heady iris
#

you spend a lot more time reading code than writing code

#

so I would optimize for that case

latent latch
#

also if you're using attibutes from naughty attributes you need to split it up such that:

[AllowNesting]
[SerializeField, HideIf("MovementType", MovementType.None)]
private Curve curveData;
public Curve CurveData => curveData;```
heady iris
#

the private set is kind of icky because it changes the meaning of your property

#

(within the class, at least; it's not public!)

placid summit
#

what about Json.NET - does it handle auto properties in any good way or you can help it do it nicely?

heady iris
#

I haven't tried serializing auto properties before

#

just hasn't come up

#

everything I'm serializing is a regular field, actually

latent latch
#

I think it does but yeah everything I use auto properties for are usually nothing im saving

heady iris
#

I'm serializing configuration data that's stored in dictionaries. I present that data to my code through properties

#

I was originally just going to serialize it that way too

#

but I don't want my saved data to break if I rename the properties

latent latch
#

I'd have an ID to the data object if anything

heady iris
#

dictionaries also meant I had to write a wacky converter that would handle dictionaries whose keys need a special converter

#

in that case, I decided to just turn my dictionaries into lists of tuples and serialize those

placid summit
#

good thoughts, thanks!

heady iris
#

I'm still a bit wet behind the ears when it comes to good serialization, though

#

I'm just getting into the phase where I need to support existing player data 😬

#

instead of just breaking everything whenever I want

placid summit
#

I have done a lot of terrible serialization, now I need to do it better - so Json.NET will be investigated for non editor stuff

heady iris
#

I have a system where scriptable objects get a GUID (literally just the asset GUID)

#

i can fetch them all from Resources and then look them up by GUID

#

and I have a converter that handles that for me

#
public class IdentifiableConverter : JsonConverter<Identifiable>
{
    public override Identifiable ReadJson(JsonReader reader, Type objectType, Identifiable existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        if (reader.Value is not string result)
            return null;

        Guid guid = new(result);

        if (IdentifiableRegistry.TryGet(objectType, guid, out Identifiable ident))
            return ident;

        return null;
    }

    public override void WriteJson(JsonWriter writer, Identifiable value, JsonSerializer serializer)
    {
        writer.WriteValue(value.Guid.ToHexString());
    }
}
heady iris
placid summit
#

yes I need to use GUIDs to id things. So do you have to convert to from string?

placid summit
#

ok so comparing GUIDs is much faster than string comparison right so better to keep?

#

or searching by etc

worn flare
#

For my enemyController i have the prefab instances of the enemy in the editor

#

since the prefab itself is not in the game

#

does that mean that it will not work

#

i instantiate the prefab, which does ofc put it in the game

#

and that does not work

#

but if i place the prefab in the scene and assign all the stuff from that to my enemycontroller it suddenly works

#

but i cant use that because then when the prefab i put in the scene is destroyed im referencing something that does not exist so it crashes

#

🦧

fervent furnace
#

gameobject in scene can reference asset

stark sinew
worn flare
#

The prefab in question is the prefab of the enemy]

#

you know how people tend to have a prefab folder

#

the prefabs in there are not in the scene

stark sinew
#

Ok, but the EnemyController is already in the Scene?
Why don't you let your EnemyController itself handle Instantiating/Destroying the Enemies?

worn flare
#

yes it is in the scene

faint otter
#

So i want to have a changing amount of rigidbodies in 2d box, i want when 2 rigidbodies with the same tag to report to a controller script that will then do something with these collisions. how would i do this? i would assume events but there will be can i add more and less events whenever i want?

worn flare
#

i have it on a cube just under the map

#

i do have it doing that stuff

#

sorry i cant explain well

stark sinew
worn flare
#

when i drag a prefab from the folder and into the scene, and then assign the parts of that to my enemyController in the editor

#

My enemycontroller works and the enemy does what i like

stark sinew
#

So, basically, your EnemyController needs to fetch some Data from your instantiated Enemies?

worn flare
#

But that is not working because eventually the enemy is killed and then i cant reference it

#

yes that is what i need

stark sinew
#

Easiest solution would be to make your EnemyController the thing that instantiates and destroy the Enemy.
That way, it could instantiate it and immediately fetch the required data, and it could destroy it and clear the reference.

worn flare
#

i dont understand

stark sinew
#

Minimal example

Enemy EnemyPrefab;
Enemy EnemyInstance;
Data SomeData;

void CreateEnemy()
{
  EnemyInstance = Instantiate(EnemyPrefab);
  SomeData = EnemyInstance.Data;
}

void DestroyEnemy()
{
  Destroy(EnemyInstance.gameObject);
  EnemyInstance = null;
  SomeData = null;
}
worn flare
#

Can i show you my enemycontroller code because i think i am doing that already

#

besides the enemyinstance = null i dont know what dat does

#

wait i think i see

stark sinew
worn flare
#

if this works i will be veryu happy because i have been trying to get my enemy to work since sunday

stark sinew
#

Feel free to share the Code (using a proper website like pastebin), as long as it's readable 😀

worn flare
#

i will ping you shortyly after i try implementing that

stark sinew
faint otter
#

well, i want one script per rigidbody/gameobject. and when it collides, itll talk to the master script and say that its had a collision

#

and then logic will run on the master script and other stuff will happne

stark sinew
#

So basically, what I said 😄
Put a Script on your Rigidbodies that uses any of the OnCollision... methods you want and inside of that make a call to your "Master".
But you should probably delay the processing of the Collision inside your Master, so it doesn't process the same collision from both sides, as in, A and B collide and both have Rigidbodies and the Script, you don't want the "Master" to be called twice for the same collision

worn flare
#

okay idk how to do it im showing you the code

stark sinew
tawny elkBOT
worn flare
#

i think most of the code is probably not stuff you need to read

#

for helping with this

stark sinew
#

You instantiate the Prefab but you don't store a reference to it? And do further work on the enemy which at that point is probably the Prefab?

worn flare
#

erm

#

perhaps

#

lololol nooooo 😭

stark sinew
#

if (enemy.GetComponent<CollisionDetection4Enemy>().collided)

#

This gets the component of the prefab, not of some instance, on the thing you pass into Instantiate, not the thing that actually was instantiated

worn flare
#

i knew i was missing something vital and its been hard to figure it out

stark sinew
#

When you call Instantiate(somePrefab), you usually want to get a Reference to the instantiated thing
myThing = Instantiate(somePrefab).

Also, your EnemyController seemingly tries to handle multiple enemies, i'd recommend to have one EnemyController for one Enemy that's being controlled

worn flare
#

okay and then do i do everything off the reference

weary swift
#

Yo! I learned the concept of design patterns and I don't really know which to choose for my project. I want to make a souls-like, at first I thought that using singletons and managers could be a good idea but I read that this could cause problem later on in development when you want to change the parameter of a function for example. Observer patterns seems like something useful in my case, but I would like opinions from experienced people on the subject if possible. I know that there isn't one perfect pattern, but I'd like to have some guidance to know what to learn. Thanks!

stark sinew
# worn flare okay and then do i do everything off the reference

This may sound easier/harder then it is, depending on your experience and use case, but you should try to make the Enemies "standalone", as in not have them require anything that's not included within themselves.

Exception being the Player, but that one could be referenced by a Singleton or a Service

worn flare
#

the two enemies is for a thing where it doubles itself every time it gets killed but i can separate from it if i must

stark sinew
# weary swift Yo! I learned the concept of design patterns and I don't really know which to ch...

Hey!

There is no "this pattern fits it all", software is mostly a combination of many different patterns and some ugly hacks in-between.

It's not like "I want to create a souls-like, what pattern do I need" but more towards "I need to build feature XY, which patterns could be used for that"

Observer Pattern for example is something that you'll likely find in every software in some style, it does nothing in itself but only helps with decoupling

weary swift
#

Ok thanks! So I should learn about famous design patterns and then try to figure out which one I should use for which problem?

worn flare
stark sinew
# weary swift Ok thanks! So I should learn about famous design patterns and then try to figure...

So, honestly, it's good if you learn the patterns and know how/why/when they do work, but you shouldn't worry about them too much, it's more important to actually get stuff done and you could always try to introduce/refactor towards patterns at a later stage.
I did both approaches, started with some patterns from the very beginning, and not doing so, and the first option comes with some technical debt that will slow down your development

stark sinew
# worn flare What is te benefeit of having the enemies standalone

Basically, testability, it's great if you can just drag and drop a prefab in your scene and it works without any additional setup.

Note that I'm not an educated professional and I'm just giving my opinions because nobody else does, burn me for any dumb things I might be saying 😄

weary swift
#

I first learned about patterns because I didn't wanted to use GameObject.Find/FindGameObjectsWithTag/putting it manually In the inspector. But if you tell me not to worry about patterns how should I get my gameObjects without using these (if it is a good idea to not use this). In my head using these prevent my project from having scalability and modularity

stark sinew
worn flare
#

can you show how i would reference the instantiated prefab in my code

weary swift
#

Because I think that manually dragging my gameObject in the inspector will prevent me from having disconnected scripts. But I'm probably wrong

#

I want to be able to modify, remove scripts without breaking all my game

#

But I don't know if it is possible, if it is something to look for

stark sinew
stark sinew
weary swift
#

So, I should do it with the inspector ?

worn flare
#

i know but i dont get it 🦧

lunar relic
#

Hey ! I would like to know if someone know a good Block/Parry system tutorial for a 2D Metroidvania game somewhere ?

stark sinew
weary swift
#

And if I want to acces variables from another script I should also use inspector ?

#

My main question is for script in reality

#

How should I access other script without breaking everything if I remove one script

stark sinew
#

If you remove one script and it breaks everything, the script is doing too much stuff.
Keep your Scripts small and simple, have them do one thing

weary swift
#

(Sorry if it's hard to understand me, it's not my main language)

dusk apex
#

You'd want to be forced to redo stuff in the Editor rather than hope nothing blows up

#

But you could attempt Finding and whatnot if you'd rather take the risk.

stark sinew
#

Thing is, you need to give us an example situation, there's not "one architecture" that works for every script you write, this currently seems to be complete on the theory side and not related to existing code, and how you'd theoretically do stuff is very subjective.

weary swift
#

Let's say I have a script PlayerStats with all it's stats. How should I get the health of my Player from the UI ?

stark sinew
#

Why would you want to get the Health from the UI in the first place?
You want it the other way around, your PlayerStats should have some Events for SomeStatsChanged and the UI would pick it up. Your PlayerStats don't care if there is a UI or not

hard viper
#

is playerstats temporary stats or hard stats?

hard viper
#

eg does playerstats have MaxHP or CurrentHP?

#

i just ask because it changes if you’re going to have multiple references

weary swift
hard viper
#

either way, I would make a monobehaviour on a UI element. UI element has a reference to your player stats, where it can read

stark sinew
hard viper
#

I expect your UI script to be able to go get access via singleton

weary swift
stark sinew
hard viper
#

lots of things in your game need direct access to your player, and to stats etc. There should be a single point of contact so everyone knows where to get that info. A singleton will help do that

weary swift
#

I think you have answered my questions! I shouldn't focus too much on design patterns for now, it's when I encounter the problem that I should look for design right? And the inspector is something useful compared to what I was thinking?

hard viper
#

it’s both

#

you should use both C# programming AND Unity’s inspector to make your life easier

weary swift
#

Ok, thanks for the help!

hard viper
#

anyway, a monobehaviour on your UI element can access your text component on the UI (eg a TextMeshPro GUI component). Then edit its text field

stark sinew
hard viper
#

you can easily make a singleton that just holds serialized references to specific gameobjects. And that’s all it does

stark sinew
#

I used stupid words, sorry.
Of course a Singleton is single and there will always be a single Singleton that's being spoken to, but that's kinda one-directional again.

I'd prefer having some Service in the middle of the objects that want to communicate with each other

hard viper
#

that’s perfect

#

you can also use a singleton mediator, if you want it to be not one-directional. But just holding references to some objects is super simple one-way connection

hard viper
stark sinew
#

It's the difference between getting a NRE or have nothing happening when the Singleton doesn't exist

#

I'd rather have nothing happening and then be like "oh, nothing happens, why? Aaah, I don't have a Player in the Scene"

hard viper
#

you know a singleton’s GetInstance method is supposed to instance it if it doesn’t exist when asking for it

#

and if your singleton just holds references, then it can check that each reference isn’t null

stark sinew
steady moat
#

Otherwise, you can get issue with performance. Having random lag spike because you did not initialize the singleton at the correct moment.

hard viper
#

guys, just use a stock singleton class implementation. which addresses issues

weary swift
#

Let's say I have two scripts on a gameObject and in the first script I want to access a variable from the other script. GetComponent<Script2>() is the way to go ?

hard viper
weary swift
#

Unique in the gameObject or in all the project ?

dusk apex
#

Making frequent changes to a single script increases the chance of error and because the Singleton pattern often becomes a major dependency, changes to it will likely cause headaches in the future - especially if working with others.

hard viper
weary swift
#

And in this case how should I process ?

steady moat
hard viper
#

i use both. it depends on the case

stark sinew
#
static PlayerEvents
{
  // Being listened to from UI 
  static event Action<float> OnHealthChanged;

  static void NotifyHealthChanged(float value)
  {
    // Called by Player when health changed 
    OnHealthChanged(value);
  }
}

I like this one better then a Player Singleton, nothing breaks if you don't have a Player, and nothing breaks if you don't have a UI

dusk apex
weary swift
hard viper
stark sinew
hard viper
#

your teeth will rot, your hair will fall out, your balls will shrivel. you’ve been warned

steady moat
hard viper
#

or only in its constructor

#

singletons are normally better in that 1) you store info on the stack, 2) info gets wiped when singleton dies. Those are the two major advantages

steady moat
hard viper
#

and it’s easier to debug

#

and you can inherit

stark sinew
# stark sinew ``` static PlayerEvents { // Being listened to from UI static event Action<...

The other thing is, you can use this kind of thing for bi-directional communication that still doesn't break if one of the sides don't exist, for example to put a RequestFullHeal or RequestPickupItem in there which the Player would listen to. (The "Events" name ofc wouldn't be appropriate anymore in that case, just call it Service or whatever)

No Player? No Listener. No Errors.

hard viper
#

he doesn’t need bidirectional communication

#

UI reads player health

#

UI reacts to player health

stark sinew
#

We should assume that he will need bi-directional communication at some point in a Souls-Like, shouldn't we

hard viper
#

no

#

not for a HUD

stark sinew
#

The HUD was an example that he gave for some context related to his question about Patterns, Modularity, Scalability

hard viper
#

this was a hud lmao

weary swift
#

I've started a war

hard viper
#

mediator pattern is more advanced, and is something you can do, and is way beyond the scope of what he was looking for

stark sinew
weary swift
#

Too much reading x)

hard viper
#

download a singleton class implementation

weary swift
#

Is it ok to use [HideInInspector] to hide a public variable ?

stark sinew
#

😄

hard viper
dusk apex
stark sinew
#

Yeah, putting some events in a static class is definitely more out of scope then having a Singleton that creates itself on demand and fetches the proper data it needs.

I do like Singletons and they have their place, but IMO not within a Souls-Like Player class

hard viper
weary swift
#

I learned about singletons yesterday and it looked really cool. The only downfall that I saw is it can cause problem in the future if you change for example the parameters of a function. You will need to change in every script the parameters when you call the function and this is bad

weary swift
hard viper
#

NonSerializedField makes a field not serialized, which also means it won’t show in inspector

#

i rarely use purely public variables

weary swift
#

purely?

steady moat
stark sinew
hard viper
#

I normally do:
This saves a myValue, makes any class able to see it, but only able to be set privately (or by inspector)
[field: SerializeField] public int myValue {get; private set;}

steady moat
#

Not having an AudioManager or IOManager seem to be a pain.

weary swift
#

I now about public private, protected (don't know what it is). Is there other things ?

#

And static

hard viper
#

This myValue can be read by any class, and only written privately. It is a property (not a field) so it does not get serialized.
public int myValue {get; private set;}

weary swift
#

And readonly

dusk apex
hard viper
#

protected means the variable is allowed to be used by derived classes. If Parent has protected int myValue, then: Parent can use it, Child : Parent can also use it, but other classes cannot

weary swift
hard viper
#

that is how I do the majority of my variables

steady moat
dusk apex
#

If you've put in the effort, it should be fine 👍

hard viper
#

The vast majority of my variables are:

[SerializedField] private int myValue; // totally private and IS serialized
public int myValue {get; private set;} // not serialized, and other classes can read the value
[field: SerializeField] public int myValue {get; private set;} // IS serialized, other classes can read, and THIS class can modify```
#

these 4 are my bread and butter

weary swift
hard viper
#

you might also want to know how to make custom properties

weary swift
weary swift
stark sinew
hard viper
#
public int MyValue {get { return _myValue;} // Shows backing field
set {
if (_myValue == value) return; // Do nothing if already the same
_myValue = value;
CallThisWheneverMyValueChanges();}
}```
weary swift
#

Ok. Thanks for all the answers, really helpful and kind of you!

hard viper
#

so you can do stuff when changing the value, for example

#

btw, showing in inspector, and serializing the field are two different things.

#

Serialize = saves value. Show in inspector = can see in inspector.
By default, inspector shows values if and only if it is serialized. But this stops if you use custom editor, or use [HideInInspector]

stark sinew
hard viper
#

changed it to public get and set

weary swift
#

I will look at all of that then. I know nothing about these concepts!

hard viper
#

fields and properties are core to programming in C#

#

to OOP in general tbh

#

just know that even if it works to just make all your variables public, don't. There are a lot of terrible side effects that will make your life difficult later

weary swift
#

Ok 👍

stark sinew
#

This is kinda unrelated to the current conversation, but you might as well check out Reference Types vs Value Types and class vs struct

weary swift
#

👽

hard viper
#

one thing at a time

weary swift
#

what is all of this

weary swift
hard viper
#

focus on just serialization and access modifiers (public/private...) for now

#

learn that, then continue

weary swift
#

👍

#

Thanks!

night storm
dusk apex
heady iris
dusk apex
#

Still seems excessive though but if he's willing to manage it then 🤷‍♂️

heady iris
#

it'd hardly be a singleton pattern if you had two things

latent latch
teal delta
#

Hey there, trying to make a simple steering behaviour (seek) in 2D and acountered this problem how can I change "desired" to be vector2?

heady iris
#

I see you're using addressables

stark sinew
night storm
heady iris
night storm
hard viper
#

My singletons, for reference

heady iris
#

I have a good number of singletons that exist in my game scenes, as well as a few that live forever in DontDestroyOnLoad

#

including the almighty GameController

hollow aurora
#

How can I make UI Toolkit Scrollview align its children from the center in a horizontal mode?

heady iris
weary swift
#

Do you guys work in the video game industry or are you just passionate ?

heady iris
#

hello ObjectiveManager!

hard viper
#

they are all good singletons. Except maybe the singleton for my single inputaction asset

night storm
heady iris
latent latch
#

they aren't bad when you know how to use them

heady iris
#

A lot of design patterns exist to reduce coupling between different parts of your game

#

You use protected and private members to limit exposure between classes

hard viper
#

yeah. like you see when I use singletons a lot, I suffer from having my references being super easy to maintain.

heady iris
#

You use events in the observer pattern to make it easier to swap things around

#

and to reduce the amount of hard-coded logic

hard viper
#

it really sucks to have my life being made easier

heady iris
#

Singletons let you produce Spooky Action At A Distance

#

everyone can see the singleton, always

latent latch
#

There's two patterns -> singleton pattern or singleton pattern with service locator pattern ;)

hard viper
#

typing intensifies

heady iris
#

For example! My game used to have a single "player" entity that was special

#

The player could have objectives, for example

hard viper
#

if there is ever any doubt that something will need multiple instances, you cannot make it a singleton. that's just asenine imo

heady iris
#

But now many entities can have objectives. I need to redesign some stuff.

heady iris
latent latch
night storm
# heady iris I think they're *prone to misuse*

am i right that there are no alternatives for singletons? for example the AchievementManager. in some random scripts you are calling AchievementManager.Instance.UnlockAchievement(achievementname) right? is that proper use of singleton by the way? and also what even would be the non singleton way to do this?

steady moat
hard viper
#

for reference, I am making a single player game. I still don't have any singletons that would make me really forced to single player

#

don't need it. not necessary. not beneficial

heady iris
#

in this case, that sounds okay -- but what about a multiplayer game..?

stark sinew
#

The non singleton way would probably be events, AchievementManager listens to stuff it cares about and decides on it's own when to unlock something, but idk

hard viper
#

also like 99% of my gameobjects get instantiated from prefabs during runtime. I literally can't serialize references

heady iris
#

If each player's game has its own achievement manager, and you aren't seeing other player's achievement managers, then that's fine

steady moat
dusk apex
# night storm so thers 2 ways to handle this? singletons or subscriptions? how do you subscrib...

The observer pattern generally has no idea who it's subscribers are which makes accessing with a static reference easier and because it's a single instance, it's fine. But managers are often boiler plates for simply decoupling direct access to references (you may be referring to a player manager that would then reference players for others - they were added as intermediaries for the sake of simply being there and most often can be excluded)

weary swift
heady iris
#

makes sense

hard viper
steady moat
night storm
hard viper
#

I use lots of singletons

weary swift
#

What are the pattern that you use the most (if this question makes sense)

heady iris
heady iris
hard viper
#

the main patterns I use are probably singleton, strategy pattern, observer pattern. There's a lot of other patterns that are really basic, but I don't even think about them because they are just part of normal business

heady iris
#

😭

stark sinew
heady iris
weary swift
#

State machine, I will look at that thanks

hard viper
#

I don't use any explicit state machines. Just enums that do a similar job

#

it's basically a finite state machine.... but not fancy

heady iris
latent latch
#

states are hard because it requires to actually debug

night storm
heady iris
#

the best way to avoid spaghetti code is to write it!

#

then to find out why it's bad for your game

#

and then to work out how to avoid that particular mistake

stark sinew
#

For me, the hardest thing about States is when they need some shared data between those, there are of course a hundred ugly ways to accomplish this, but idk for a clean way besides some type of DI

heady iris
#

look at me, telling people "make your game" while I'm sitting here, not making my game

#

back to work!

steady moat
latent latch
#

Or another layer for networking where you'd have NetworkManager with a set of Players, but clients would also already cache a reference to themselves

steady moat
#

This is what I have at the moment for the Manager. If I had to make it per player, I would change the progression handling part.

public class AchievementManager : Manager<AchievementManager>
{
    public List<AchievementDefinition> m_AchievementDefinitions;
    public EventManager EventManager { get; private set; } = new EventManager();

    private Dictionary<AchievementDefinition, float> m_Progress = new Dictionary<AchievementDefinition, float>();

    public void Awake()
    {
        foreach (AchievementDefinition achievementDefinition in m_AchievementDefinitions)
        {
            achievementDefinition.SubscribeEvents(EventManager);
        }
    }

    public void OnDestroy()
    {
        foreach (AchievementDefinition achievementDefinition in m_AchievementDefinitions)
        {
            achievementDefinition.UnsubscribeEvents(EventManager);
        }
    }

    public void UpdateProgress(AchievementDefinition definition, float progress)
    {
        if (!m_Progress.ContainsKey(definition))
            m_Progress.Add(definition, 0.0f);

        if (m_Progress[definition] >= progress)
            return;

        m_Progress[definition] = progress;
        PlatformManager.Instance.UpdateAchievement(definition, progress);
    }
}
hard viper
#

Question on assemblies, since I learned about the issues where every asmdef needs to reference EVERY single dependency. How do I make an asmdef that automatically figures out: if I depend on X depends on Y, then I depend on both X and Y?

late lion
hard viper
#

ok, I think I'm getting the hang of it a little

#

but this still seems like it could become really tedious

worn flare
#

@stark sinew can you pls tell me if ive applied what you said correctly

hard viper
#

ok so.... lets say that I have 10 classes that all need special internal access to each other. A couple of these 10 classes needs access to my main assembly, and my main assembly needs access to that one main class. Is there any way to split their assemblies?

#

maybe this is just the wrong way to use assemblies

night storm
#

also arent assemblies completely useless if you got singletons? because all your singletons are being called from any of your scripts. AchievementManager singleton would need to be called from everything that can give you an achievement (and that could be anything)

steady moat
night storm
steady moat
night storm
steady moat
#

In other words, the implementation of the achievement would be in a different assembly that the code handling the logic of the achievement.

#

In the general assembly of the game.

[CreateAssetMenu(menuName = "Definition/Achievement/DefeatEnemiesUsedAchievementDefinition")]
public class DefeatEnemiesUsedAchievementDefinition : AchievementDefinition
{
    public int m_Amount;

    public override void SubscribeEvents(EventManager eventManager)
    {
        eventManager.Subscribe<EnemyDefeatedEvent>(OnEnemyDefeated);
    }

    public override void UnsubscribeEvents(EventManager eventManager)
    {
        eventManager.Unsubscribe<EnemyDefeatedEvent>(OnEnemyDefeated);
    }

    private void OnEnemyDefeated(EnemyDefeatedEvent e)
    {
        AchievementManager.Instance.UpdateProgress(this, (float)e.m_AmountDefeated / (float)m_Amount) ;
    }
}

In the Achievement Assembly

    public abstract class AchievementDefinition : ScriptableObject
    {
        [SerializeField]
        private string steam;

        [SerializeField]
        private string xbox;

        [SerializeField]
        private string playStation = "";

        public string ID
        {
            get
            {
#if UNITY_EDITOR
                return "";
#elif UNITY_XBOXONE || UNITY_GAMECORE_XBOXONE || UNITY_GAMECORE_XBOXSERIES
                return xbox;
#elif UNITY_PS4 || UNITY_PS5
                return playStation;
#elif UNITY_STEAM
                return steam;
#else
                return "";
#endif
            }
        }

        public abstract void SubscribeEvents(EventManager eventManager);
        public abstract void UnsubscribeEvents(EventManager eventManager);
    }
night storm
#

ok, thanks!

vast patio
#

Hello, is it ok to ?.Invoke() an unityevent in awake? im wondering because some gameobjects might not be done with their awake? I also just wanna invoke it only one time and i keep enabling and disabling the script during runtime

soft shard
# vast patio Hello, is it ok to ?.Invoke() an unityevent in awake? im wondering because some ...

Start will also run only once on a objects lifecycle, so if you want to be sure a dependency in Awake is ready, you can call it in Start instead, often Awake is best used for data you know you have like GetComponent on a object you know has the component, though technically theres nothing wrong with trying to do a ?.Invoke theres just of course a chance the invoke never happens, because the order of Awake is up to Unity and AFAIK, is mostly random/inconsistent - and if your curios: https://docs.unity3d.com/Manual/ExecutionOrder.html

teal delta
#

how can I rotate enemy acording to his movement? this is my enemy movement script

vast patio
stark sinew
# worn flare <@610365119142166548> can you pls tell me if ive applied what you said correctly

sorry i wasn't in front of PC.
it's "more correct" but still has some major flaws.
for example

enemyInstance = Instantiate(enemyPrefab, enemyPosition, PlayerRot);
enemyInstance = Instantiate(enemyPrefab, enemyPosition, PlayerRot);
{
    health = 3;
    health = 3;
}

this won't work as you expect.

  1. you are overriding the Enemy Instance, if you want to handle multiple Enemies from that single class then you need to put them inside a Collection (List<T> for example) and access them by a ID or something.
  2. the { ... } block is not setting the Health for the Enemies, it's setting the variable inside that class to 3, twice in a row. the {} are obsolete there, your IDE should tell you that they are not needed because it doesn't know what you actually want to do.
    you want Health to live on the Enemy itself, not on the EnemyController, because different Enemies will different Health Values.

another issue are this parts

Vector3 enemyPosition = enemyInstance.transform.position; // In your Update

enemyInstance = Instantiate(enemyPrefab, enemyPosition, PlayerRot); // In your Update as well

if (Physics.Raycast(enemyPosition, directionToPlayer, out hit, Mathf.Infinity)) // In your CanSeePlayer

you have a variable in that class called enemyPosition, you don't want to declare another local one inside of the Update, you want to assign it to the variable that lives in that class, which again doesn't work as you want it to do if you're managing multiple Enemies inside of it.
The EnemyPosition should (obviously) go on the Enemy itself, not in the Controller

terse turtle
#

I want to learn C# so I bought a C# book. However, it was published around 2002. Is this book still relevant to learn from?

stark sinew
worn flare
#

how do i put it on the enemy itself when its an instantiation

stark sinew
#

your enemyPosition is only a copy of enemy.transform.position .. you don't need that variable at all.
in general, i think my suggestions won't fix your Script, you need to rethink what you are trying to do.
people in here might be well capable of helping you further if they knew your goal.

worn flare
#

Okay

#

its so over

stark sinew
#

it's definitely not the best approach 😄
for example, why does the EnemyController check if the Enemy sees the Player, why doesn't the Enemy itself know about it?
Why doesn't the Enemy know about it's own Collider or Renderer?
why does it know about the Players Gun?

You can solve most of the problems if you just scrap the EnemyController and introduce a proper Enemy class which is, as i advised earlier, standalone

worn flare
#

the collider script i have on the enemy already breaks the game when it is killed because then im referencing something that does not exist

#

i need to know how to have everything not break if something on an enemy is referenced before i go and add more things to it

tight fjord
#

why does the navmesh agent doesent send a error instead of not moving the NPC?

#

I try to change the target but the NPC starts standing and running in place if I try to change the navmesh target

rigid island
#

not enough info

tight fjord
#

me to, because it doesent send me a error.

whole garden
#

does someone know a lot about unity Facepunch and online with steam ?

stark sinew
tight fjord
#

there is agent and it is walking but if I want to change the route like following another empty gameobject, it stops moving completely.
I'm not even sure how to disable it because its not C#, its Unity specific what a navmesh Agent is and works.
I tried to disable the gameobject what the navmesh agent is targeting on but it doesent help.
I tried to reset the path and set a new one with:

    [SerializeField] private Transform PlayerTargetPosition;


        var_navMeshAgent.ResetPath();
        var_navMeshAgent.destination = PlayerTargetPosition.position;

But IDK its not helping.

stark sinew
tacit swan
#

how can i detect if an ontriggerenter2d collider is on a certain layer?

tight fjord
tacit swan
#

does collider.gameObject.layer return the string or an int?

#

it seems to return an int but is there a way to compare it to some LayerMask layerMask ?

stark sinew
tight fjord
#

The NPC is still running on place, wtf.

stark sinew
stark sinew
tight fjord
#

ok, I outcommented every resetPath with "//" and now it works, thanks.

heady grove
#

Hi All,
Is there a good tutorial on what pattern to use to manage UI states, for example:

  1. Idle UI
  2. Building a building (dragging it)
  3. When you are placing a building you have a pop-up to configure it
  4. If during step 3 you press esc instead of enter - you go to step 3 where you are dragging the building around
sharp valve
#

is Screen.fullscreen always false in the editor?

stark sinew
#

to manage UI states ..
StateMachine? 😄

heady grove
#

so have no clue where to start

stark sinew
stark sinew
heady grove
#

ty!

normal arch
#

i can show more scripts if you're confused on what's going on

stark sinew
#

you always call ChangeHeightLevel, maybe you want to return out after the Debug.Log?

normal arch
#

return out?

#

what is that for

knotty sun
#

you are setting dynamicColliderHeightLevel on the collider but using another variable to add to the list

stark sinew
# normal arch return out?

return so your ChangeHeightLevel doesn't run if if(colHeight.startingColliderHeightLevel + (int)entityHeight == 0)

normal arch
normal arch
knotty sun
#

no you did not

#

colHeight.dynamicColliderHeightLevel =
is not
[dynamicColliderHeightLevel]

normal arch
#

imagine dynamicColliderHeightLevel is n, ChangeHeight level adds it to the nth list in the list of lists, which may be confusing i know

#

so i did set dynamicColliderHeightLevel and use it

knotty sun
#

you are the one that is confused, I can read code

stark sinew
#
HeightManager.heightManager.levels[currentColliderHeightLevel].Remove(col);
HeightManager.heightManager.levels[dynamicColliderHeightLevel].Add(col);
currentColliderHeightLevel = dynamicColliderHeightLevel;

what exactly is supposed to happen here, can you just give a mocked example with actual numbers? xD
do you eventually want to do this in a different order, Remove -> Change Variable -> Add?
the code looks good, can't spot issues with those 2 snippets

normal arch
knotty sun
#

sorry, my bad you call the method on the changed instance

normal arch
#

the problem i'm having is that it randomly adds the colliders to the 0th list (yeah i'm calling it that) when it shouldn't

#

not sure if this matters but it also never added more than one list to the 0th list at a time

somber nacelle
twilit scaffold
#

oops 🙂

wheat oasis
#

Oh sorry again 😭

twilit scaffold
#

no worries, that was my fault

normal arch
stark sinew
normal arch
normal arch
round violet
#

is there a way to retreive the LookAt without applying it ?

stark sinew
round violet
#

ty

#

but i dont know well how Quaternions work, how can i set the Z rotation with a Quaternion ?

normal arch
pine carbon
#

how to change the head position of the armature

#

it doesnt change

naive elk
#

Hi. I have set waypoints for enemies, and if the player is not nearby, they should move between these waypoints. In the editor, it works as intended without any issues, but on the phone, only the first type of enemy I created is moving correctly, while the others are attempting to go to point 0. Additionally, there are three types of enemies, and I created a prefab for the first ones and added the others. There is a problem with the others. I tried removing the prefab connection, but it's still the same. However, in the editor, it works correctly in both ways as it should. Can someone help me about it please

weary swift
#

Yo! I have two scripts PlayerInput and PlayerLocomotion. I want to add rotation logic depending on the Input. Should I create a third script PlayerRotation or is it overkill ? I don't know where to draw the line of "one class = one thing"

normal arch
#

i think those two scripts are too much in the first place

#

they should probably all be in the same script

#

or put the rotation in the playerlocomotion script, but definitely not 3

weary swift
#

Ok thanks! How can I know when to stop applying one class = one thing ?

rigid island
#

read up on Single Responsibility

#

if your script is very clear on what it does no reason to cram everything in 1 script

#

debugging / extending anything later will be painful

normal arch
weary swift
# rigid island read up on Single Responsibility

That's what I'm talking about. But In my case rotation is closely related to locomotion, but it isn't necesseraly the same concept. Following the srp I should create a third script but I don't know if it's overkill

weary swift
#

Yes

rigid island
#

Up to you how you define the responsibility, these are just outlines for keep clean and clear code that is simplle to addon

normal arch
#

just bumping this up here again, i haven't had a fix for it yet.

rigid island
# weary swift Yes

If you consider it part of "Locomotion" then its okay to do it, if you think there will be more than just rotating or what if you need it to rotate something else that doesn't move?. Things like that

weary swift
#

I think I'm gonna create another script, and if someday in the future I see that the script isn't moving that much I will move it to the locomotion script. This is a good idea?

rigid island
weary swift
#

Ok, thanks!

hoary mason
#

despite me editing the collider's values on the animation and the animation playing, they don't actually change in the game

rigid island
hoary mason
#

that's just me selecting them

rigid island
#

Ohh I see

#

still looks weird

#

show the animator

#

how do you transition to this clip, nd are you sure the keyframes aren't skipped?

hoary mason
rigid island
hoary mason
#

probably yeah

#

I transition through an animation controller

rigid island
#

hmm yeah the keyframes seem to be only on the first frames, so def check transitions arent skipping the keyframe

hoary mason
#

i then put it first and last frames and it still didn't work

rose coyote
#

I'm using a ruleTile, is there a way to have the ruleTile adjust if it finds any tile is found (aka not one part of the ruleTile rules? i can share code and picture of what's occurring if needed

twilit scaffold
#

why Random.Range is max Exclusive, i do not know

normal arch
#

is that a question?

twilit scaffold
#

is it required to be? it can be, or it can be a statement

normal arch
#

like do you want a fix?

twilit scaffold
#

more a curiosity thing.. is there like a Random.RangeInclusive?

rigid island
#

floats

twilit scaffold
#

true

normal arch
#

you can have a random.rabnge with floats yeah

rigid island
#

or just put 1 more int above

normal arch
#

and cast it to an int or round it

twilit scaffold
#

sounds good. thanks guys

normal arch
#

yw

rigid island
#

(don't do it its a joke)

#

but notice how with .Length it does become inclusive

twilit scaffold
#

interesting! hmm. something to keep in mind

faint brook
#

in one my my projects I am using a the google sheets api. This uses google authentication api which uses Newtonsoft.Json. My project throws the provided error when build with webgl when ever a google sheets api call is made. Through research I have determined that this error is caused by AOT. following this guide: https://github.com/applejag/Newtonsoft.Json-for-Unity/wiki/Fix-AOT-using-link.xml I created a link.xml file and included it in my assets folder. here is the contents of my link file ```xml
<linker>
<assembly fullname="AssemblyCSharp">
<type fullname="usesJson.handleLogin" preserve="all"/>
<type fullname="usesJson.USER" preserve="all"/>
<type fullname="Google.Apis.Auth.OAuth2.JsonCredentialParameters" preserve="all">
<method signature="System.Void .ctor()"/>
</type>
<type fullname="Google.Apis.Auth.OAuth2" preserve="all"/>
<type fullname="ewtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject" preserve="all">
<method signature="System.Void .ctor()"/>
</type>
<type fullname="ewtonsoft.Json.Serialization.JsonSerializerInternalReader" preserve="all"/>
</assembly>
</linker>

GitHub

Newtonsoft.Json (Json.NET) 10.0.3, 11.0.2, 12.0.3, & 13.0.1 for Unity IL2CPP builds, available via Unity Package Manager - applejag/Newtonsoft.Json-for-Unity

hoary mason
#

I asked at animation but asking here just in case too

#

I'm trying to change my collider's size and offset through my animator so that it changes when I change direction, but when on runtime it stays at default. Yes I did check that the animations are being properly played. Then to test I tried setting the size at (0,0) at the first frame and then at (1,1) after one frame, and instead of the size changing like that, it became the default size X and Y values +1

weary swift
#

Yo! In general should I Use Unity or C# events? Right now I have a PlayerInput script and when I press a certain key I want to call an event that will do something in another script. What is the best here?

quartz folio
weary swift
#

Perfect, thanks!

worn flare
#

helllo

#

how come the enemies i instantiate after the first enemies death

#

do not do anything, unlike the one which is instantiated in the start function which works properly

worn flare
somber nacelle
#

you do know you can ask follow up questions, right? don't just crosspost to a different channel because you didn't understand the reason provided to you.

#

the answer is still the same though. you only operate on the most recently spawned enemy because you're only storing a reference to one enemy

worn flare
#

my apologies

#

how would i have it not store only one reference

somber nacelle
#

there are beginner c# courses pinned in #💻┃code-beginner if you do not know how to create an array or a list.
praetor's second point about your spawner also managing the behavior is also a good point. why not have the enemy objects handle their own behavior and just make the spawner handle spawning them

worn flare
#

i have been having issues with that since i cant assign anything thats not also a prefab to a prefab in the editor

somber nacelle
worn flare
#

this is good knowledge

spice dagger
#

How would i edit a .data file

somber nacelle
spice dagger
#

convert it to human readable

somber nacelle
#

why not just write it in a human readable format in the first place?

spice dagger
#

Because the file isnt from my game

#

i just want to edit the file

#

figured i might as well come to this server

#

as its made in unity

somber nacelle
#

modding discussions are not permitted here. if you want to modify a game then go to that game's modding community for help.

spice dagger
#

the modding community doesnt exist as its an android game but alright

indigo hound
#

Hey there, in my game I use the following code to create an instance of PlayerMovementStrategy, but it gives me this warning. It says to use AddComponent, but when I try that, it gives me an error. What would be the best way to solve this to not get any errors or warnings?

Option 1: Gives Warning

public void CreatePlayerMovementStrategyInstance(PlayerPowerupState currentPlayerPowerupState)
    {
        currentPlayerMovementStrategy = Activator.CreateInstance(currentPlayerPowerupState.playerMovementType) as PlayerMovementStrategy;
    }

Option 2: Gives Error

public void CreatePlayerMovementStrategyInstance(PlayerPowerupState currentPlayerPowerupState)
    {
        currentPlayerMovementStrategy = currentPlayerPowerupState.AddComponent<PlayerMovementStrategy>();
    }
latent latch
#

what is this format

#

!code

tawny elkBOT
round violet
#

Probably a useless question, but is this statement still true ?

Should i use jagged arrays rather than multidimensional arrays ?

latent latch
#

if that is true I laugh

simple egret
#

Considering Unity uses a .NET version that released in 2012, most likely yes

round violet
latent latch
#

yes that something as simple of an array of arrays

#

is that slow

somber nacelle
#

I'm genuinely curious if that is true so i'm going to write a quick benchmark for it and find out

round violet
#

Ty

lean sail
latent latch
dusk apex
latent latch
#

Need type info

dusk apex
indigo hound
#

I think I got it, I just had to remove the monobehaviour on the classes I used which removed the warnings and errors. I found out that a monobehaviour has to be attached to a gameObject which I didn't know, but now I do

round violet
#

This page wasnt updated

#

But is unity now using a newer version of dotnet ?

somber nacelle
#

yes, not the newest, but certainly newer than unity 5 was using

lean sail
round violet
#

Lets wait the benchmark ig

indigo hound
dusk apex
hard viper
#

if playermovementstrategy is a Monobehaviour (it should not be), then you want to AddComponent it so other components can find it easily, when tied to the gameobject

#

Monobehaviours get attached to GameObjects because that is how Unity knows to get calling Awake, Start, OnEnable, Update, etc…

#

but that is unnecessary overhead for a POCO (plain old C class), that doesn’t need any of that behaviour

#

your PlayerMovementStrategy should typically have 0-2 fields in it, because the whole point is mostly to pass on the strategy. Ie the specific function/algorithm you want to use

#

it’s job isn’t to maintain/manage major aspects of a player’s state, if that makes sense

indigo hound
#

Yeah I actually never learned that it's supposed to be attached to a gameObject. The rest I somewhat knew, but thanks for the heads up anyways!

hard viper
#

it’s ok. learning is just a part of the process

somber nacelle
# round violet Before going to sleep i found this <https://docs.unity3d.com/Manual/BestPractice...

Benchmark Code: https://paste.mod.gg/uxdjbkfetrgu
Setup used: Unity 2023.2.3 targeting .net standard 2.1 with Performance Testing Extension for Unity Test Runner

So fully iterating through the 3d array is slower than fully iterating through a jagged array of the same size using for loops. It is a rather significant difference at about 4 times the median speed
Randomly accessing an index is so fast for either that the difference isn't even something worth worrying about.

heady iris
#

That's really curious.

latent latch
#

3D array more jagged than the jagged array it seems

hard viper
#

it’s worth noting the random access is 100 accesses, and full array was 10^6 accesses in that code

#

it’s super weird that jagged is faster than 3D array

somber nacelle
#

Yeah had to do 100 access for random access to even get any time on them. So really unless they plan to iterate their 1 million element arrays all in a single frame, there really isn't much point in worrying about the performance impact of either.
The fact that there is such a huge difference in the sequential access is rather curious though

hard viper
#

arrays in general are fast as fuck

#

it’s their job

#

a job they are very good at

#

it’s weird since i expect a jagged array to access by 3 pointers, while a 3D array to be doable by one pointer + fast math

craggy veldt
#

Jagged array is just regular array under the hood, it should be faster than multidim

drowsy crest
#

For prefab instances that were placed in the scene in the Editor by hand, should I be able to destroy these from script using Destroy(prefab)?

unreal temple
#

No

#

Actually just no, not ever. You need to destroy the instance, not the prefab. The prefab will be the object was that was copied.

drowsy crest
#

So you drag it from the project folder, into the scene, it's an instance of that prefab. Then during runtime, I target it with script and try to destroy it so it's removed from the scene. It doesn't work

unreal temple
#

With the little info you're giving, I suspect you're probably accidentally destroying a compponent on the gameobject instead of the gameobject inself

#

It's an easy mistake to make

drowsy crest
#

Ok but it SHOULD be possible, right?

unreal temple
#

i.e. Destroy(someComponent) instead of Destroy(someComponent.gameObject)

drowsy crest
#

ok that's exactly what I'm doing, so there you go

unreal temple
#

okay, cool

drowsy crest
#

Was JUST about to give up on that approach

faint otter
#

Gday everyone, i have a script on an object that also has the same script attached, when these objects collide they are meant to spawn a singular object. but this is not the case though

#

it spawns two (because the script doesnt know the other script exists i believe?)

#

whats one of doing this, could i remove the script from the other object to combat this?

lost mirage
#

One possible solution is to add a flag like bool hasSpawnedObject. Whenever it collides and hasSpawnedObject is false, spawn the object, then if the object it collided with is the same type, set its hasSpawnedObject flag to true. Else, if hasSpawnedObject is true, then reset it

OnCollision(EventArgs e) {
    if (hasSpawnedObject) {
        // reset flag
        hasSpawnedObject = false;
        var collidedObject = // Get the collided object
        collidedObject.hasSpawnedObject = false;
    }
    else {
        // Spawn the object //


        var collidedObject = // Get the collided object
        collidedObject.hasSpawnedObject = true;
    }
}

There may be a more efficient method though. This is just what came to mind

faint otter
#

well on both scripts the Event happens at the exact same time, right?

lost mirage
#

I'm not sure

cosmic rain
faint otter
#

then why on earth is it spawning two, is luckybread's answer correct?

cosmic rain
cosmic rain
faint otter
#

ill try luckybreads method than ill see what i can do about a spawner manager

#

in the mean time, what would that look like?

#

So i want to have a changing amount of rigidbodies in 2d box, i want when 2 rigidbodies with the same tag to report to a controller script that will then do something with these collisions. how would i do this? i would assume events but idk - I asked this question yesterday and nobody got back to me

#

essentially what youve told me to do

cosmic rain
cosmic rain
faint otter
#

Aha

#

Luckybread's method worked

#

Thanks for the suggestion though, ill keep it in the backlog if i find more errors

shell scarab
#

If I needed a word that describes what Classes, Structs, Records, Enums, Interfaces, etc. were, what would it be? Types?

craggy veldt
#

in C#, classes, structs, and records are all user-defined types

#

for Interfaces you can think of it some sort of a contract

#

much quicker if you just google these

knotty sun
shell scarab
knotty sun
#

that's 2.5 words.
Type definition keywords is about as small as I can get it

#

or even object definition keywords

shell scarab
#

structs are not objects

#

neither are interfaces

#

idk ab enums, don't think so tho

knotty sun
#

in this statement

public class MyClass {

the type is MyClass not class
structs are objects
and interfaces can only be used in combination with an object and can be treated as such

#

as for Enums, because they rely on an underlying primitive type, which are also objects, they too can be thought of as objects

cosmic rain
#

Basically an instance of anything is an object.

knotty sun
#

correct

#

object of type xyz

swift falcon
#

Greetings, maybe the correct place to ask. Newbie here, was wondering maybe someone can explain how unity and rpg maker C# differ?

#

Same language, but they feel so different to code

knotty sun
#

In one word, API. The C# used is identical except possibly for version, the API calls will be wildly different

swift falcon
#

Way more clear and huge of unknown again ^^

#

Based of this, can I guess that plugins that would make the coding similar is not likely?

#

Actually where would I look for unity plugins?

knotty sun
#

not at all but, would not be that hard to make

swift falcon
#

Could a newbie do it?

knotty sun
#

no

swift falcon
#

ohhh, yay and ohhh

knotty sun
#

you would need to know the API's of both systems really well

#

btw you can find Unity plugins both on Github and the Unity Asset Store

spiral yacht
#

hey anyone know why when using fixed update the detection for space bar like barely works but removing it then it starts working fine? i thought it was supposed to be better to use fixedupdate for like physics things, or atleast thats what ive heard, sint jumping related to physics?

lost mirage
#

input detection itself is not related to physics

knotty sun
#

physics, yes. catching Input, no. So you need both, Catch Input in Update, consume it in FixedUpdate for physics

lean sail
# spiral yacht hey anyone know why when using fixed update the detection for space bar like bar...

fixed update does not run parellel to your frames, while GetButtonDown is only true for one frame. if there are 2+ frames between a physics loop then its likely going to be set to true and back to false before FixedUpdate.
You can actually keep that jump code inside Update, because your ForceMode is impulse, which is a one off thing. It happening once in update vs fixedupdate will not have a noticeable difference.
As for the line above, where you AddForce(0, 0, forwardForce * Time.deltaTime), you should remove the Time.deltaTime and keep that inside FixedUpdate. The equations used by addforce already take deltaTime into account, so you shouldnt be using it here.

spiral yacht
#

thanks im very new to this all, had no idea addforce already accounted for it, thanks so much!

swift falcon
long scarab
#

how can I get a transform to rotate with a game object? the InteractionPoint follows the player in xyz axes but it doesn't turn with the player

somber nacelle
#

Sounds like Body is the object that is rotating, not Player so you have a couple options. You could make InteractionPoint a child of the Body object or you could use something like a rotation constraint

long scarab
#

I'll probably just go with making it a child of body since it's going to be following it around anyways, but whats a rotation constraint?

somber nacelle
#

a component that does exactly what it sounds like it does

long scarab
#

oh its a component

#

gotcha

round violet
#

hello,
i got an array of type myCustomStruct

i am filling it in the inspector
the issue is that if later i edit my struct in my script (name, parameters, remove/add), the array/struct resets

is there a way to prevent this lose ?

#

the solution would be filling the array directly in the script, but i would like to avoid that

#

well apparently its only renaming the var of the struct that resets the values in the inspector (which is normal)

lean sail
fluid geyser
#

Quick Question:
Is it possible to disable/enable Character Controllers for my Third Person Controller at will, (for instance, when entering/exiting a certain trigger), in the code?

knotty sun
cold egret
#
  • When i use the graphics api to draw different meshes with the same material within a single frame, will it all go in one batch?
cosmic rain
round violet
#

i would like to draw stuff with gizmo, the issue is, i can only use Gizmos methods in specific methods (ie: OnDrawGizmosSelected)

how can i decie in my code "when" i want to draw ?

example:
lets say i have a loop iterating 10 times, with a 1s delay, and at the end of each delay i draw 1 sphere

how would this be done ?

fervent furnace
#

cross "method" communication

late lion
hollow aurora
#

I am trying to write an editor script to generate textures of prefab previews and then stroe their references into a scriptable object.

 File.WriteAllBytes(filePath, tex.EncodeToPNG());
 var preview = (Texture2D)AssetDatabase.LoadAssetAtPath(filePath, typeof(Texture2D));
 building.preview = preview;

The texture gets created but the preview returns null for some reason. Any tips?

knotty sun
hollow aurora
#

I did update the code as such but im still getting the same issue. And the textures seem to randomly disappear sometimes not sure why

            var tex = AssetPreview.GetAssetPreview(building.prefab);
            var previewImageName = building.building + "_preview";
            string filePath = Path.Combine(previewImagePath, previewImageName + ".png");
            File.WriteAllBytes(filePath, tex.EncodeToPNG());
            AssetDatabase.ImportAsset(filePath);
            AssetDatabase.Refresh();
            var preview = (Texture2D)AssetDatabase.LoadAssetAtPath(filePath, typeof(Texture2D));
            building.preview = preview;
knotty sun
hollow aurora
#

I just noticed a warning that my path is invalid

#

which is odd because it was fine for the WriteAllBytes

knotty sun
#

that wont help

hollow aurora
#

LoadASsetAtPath maybe has an issue with combining "\" and "/" in one path

knotty sun
#

what is your path?

hollow aurora
#

Invalid AssetDatabase path: C:/redacted/Repositories/redacted/Assets\ScriptableObjects/Buildings Tiles/Previews\Watermill_preview.png. Use path relative to the project folder.

knotty sun
#

yes, LoadAtPath expects a relative path starting at Assets

#

and indeed only / not \

hollow aurora
#

This is my path now

#

It manages to load the asset but Im still getting the warning O_O

#

ah nevermind my bad

#

Thanks for help @knotty sun !

round violet
fervent furnace
#
public void Update(){
  load data
  i want lateupdate to process
}
public void LateUpdate(){
  if(update want me to run){
  }
}
```how to do that
round violet
#

well, i dont see the usecase, but here is my guess:

string _data;
bool canUpdateProceed = false;

    private void Update()
    {
        _data = "its me ";
        canUpdateProceed = true;
    }

    private void LateUpdate()
    {
        if (canUpdateProceed ) {
               _data += "mario";
        }
    }
    //after the LateUpdate you will have "its me mario", since LateUpdate is called after Update

edited because you wanted update want me to run

fervent furnace
#

yes

round violet
#

if after you load the data, you always want LateUpdate to proceed, you dont need the bool, since LateUpdate is ALWAYS called after Update

fervent furnace
#

OnDrawGizmos is called once per update cycle

craggy veldt
#

relying on execution order sounds like a bad idea, make a queue system instead

round violet
#

im lost

fervent furnace
#

you want your ondrawgizmos draw something once some conditions in other method was reach

round violet
#

oh sorry i thought you were asking a question for yourself, the how to do that got me

round violet
fervent furnace
#

a more general way to solve this is to implement queue system as slimstv have said, you load the command in other method that in ondrawgizmos you dequeue all stored commands

round violet
#

okay, how do you "load a command" then dequeue ?

vapid parcel
#

why can't I add 2 strings together?

fervent furnace
#
[StructLayout(LayoutKind.Explicit)]
public struct command{
  enum command_type;
  [FieldOffset(0)]public command_type type;
  [FieldOffset(8)]public type1 data_for_command1;
  [FieldOffset(8)]public type2 data_for_command2;
  [FieldOffset(8)]public type3 data_for_command3;
  .......
}
```i would do this, others will suggest you having an interface
```cs
public interface IDraw{
  draw();
}
public DrawBox():IDraw{
  Gizmos.DrawCube(XXX);
}
round violet
#

prob because in unity/c# strings cant be interpretd like list

#

not like python

fervent furnace
#

code[0] is not string, it is char

round violet
#

oh okay so it does work