#archived-code-general

1 messages ยท Page 380 of 1

plucky inlet
#

where do the lines come from? Its not really clearn, what your setup is

eager fulcrum
#

my lines come from 4 vertices

#

one sec

mossy snow
#

pro tip: make the problem smaller when debugging

foggy dagger
#

this is my code:

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

        Vector2 MousePos = Camera.ScreenToWorldPoint(new Vector3(InputHandler.MousePosition.x, InputHandler.MousePosition.y, -Camera.transform.position.z));

        Gizmos.DrawWireSphere(MousePos, 1);
        Gizmos.DrawWireSphere(transform.position, 1);


        Gizmos.DrawLine(transform.position, ((Vector3)MousePos - transform.position).normalized * Distance);
    }
dusk apex
#

Log the direction, mouse position and transform position

dusk apex
foggy dagger
dusk apex
#

DrawLine(position, MousePos);

#

(Excluded the minor details)

foggy dagger
#

if this was purely a debug that would work but i need it to be a direction with a constant distance (to ensure the boomerang always flies a specific distance before coming back)

dusk apex
foggy dagger
#

to make myself more clear im trying to debug the direction not how i draw it

dusk apex
#

Your draw line function is being used incorrectly

foggy dagger
#

i replaced the line and this showcases how the red circle (the direction) strays off of the actual line if it were to go in the direction correctly

#

im using debug to visualize it better, in gameplay the boomerang strays aswell

dusk apex
#

Fix the debug first then attempt to fix the actual object.

#

Your draw line is definitely wrong as is

lean sail
#

The direction looks fine otherwise

idle river
#

ive been trying to make a grid system for a project but i just cant seem to fully understand it

#

im trying to make a puzzle game where the pieces move like chess pieces

vestal arch
idle river
#

im an idiot basically

vestal arch
#

we can't really help with that
if you have a specific issue you want to actually ask about, we could help with that, but we're not going to reexplain the whole grid system when there's already plenty online

bleak meadow
#

Hi! I was wondering if someone could help me. My electricity went, and now when i started my project again this error won't let me press play. I can't find anything on google eighter ๐Ÿ˜ฌ

somber nacelle
#

make sure all of your packages are up to date. after ensuring they are and if the issue persists then close the editor and open up the Library folder within your project files and delete the PackageCache folder. Then open the project again and unity will force your packages to reinstall which should resolve that

bleak meadow
somber nacelle
#

it will reinstall the versions currently installed in the project which is why i said update them first

civic girder
#

Question:
I'm making a menu based game (think rpg with menus). Since my "turn phases" are defined, I chose to make the player into an FSM.
I want to handle a key input (let's say space key) differently depending on what phase I'm in.

Example:
Action picking phase -> the space key selects an action
Target Picking phase -> the space key selects a target

Would triggering an event from the player when the key is pressed and having the state listen to that and act accordingly be logical?
or is it better to just have each state handle it's own input? (as there may be states where the player cannot move)

steady moat
#

Obviously, you need to factor in the player whenever you read inputs. Either by listening to its input or "pooling" them.

civic girder
civic girder
steady moat
#
player.Input.OnGetKeyDown += ...

OR

if(player.Input.GetKeyDown(SpaceBar))
civic girder
#

Can't I just
Input.GetKeyDown?

Or is there a difference when called on the player object?

steady moat
#

Yes you can, but as I said it is better to use the player object. It give you more control.

#

By example, you can easily define a control mapping schema where if you do a Input.GetDown everywhere it is going to be tricky.

#

Also, if you were to replace the player an AI, it would be easy to simply simulate the input to make your ai.

civic girder
#

Ahh

#

Thanks ๐Ÿ™๐Ÿป

steady moat
#

If you have multiple device (Keyboard, Phone, Controller) it can make it eaiser

#

Finally, if you have more player, you will be able to handle this case as well.

#

So yeah, 4-5 reasons to why you should use the player instead of reading it directly.

tawdry jasper
#

I have a bunch of extension methods, and I just realized looking at them that they are declared static - not sure if this is for csharp reasons or unity reasons. Can someone explain to me why that is, and also can I declare a true static helper? So I can call Quaternion.SomeHelper(), rather than needing a quaternion instance?

Is this a good approach generally, or should I just decalre a static QuaternionHelpers and call that?

leaden ice
#

That's C#

#

nothing to do with Unity

#

If you want to add static functions directly to Quaternion, I believe you should be able to do this:

public partial struct Quaternion {

  public static void MyNewHelperFunction() {}
}```
#

That should let you do Quaternion.MyHelperFunction();

#

But if that doesn't work - your best bet is just to define your own static functions elsewhere.

knotty sun
leaden ice
#

Fair enough

#

In that case yeah - you're SOL since C# doesn't support static extension functions

#

it doesn't buy you too much though.

#

Just Quaternion.MyFunc() instead of MyClass.MyFunc()

vagrant oasis
#

should i keep my player script in one script or should i split it into multiple ones like InteractionController, MovementController etc??

rigid island
#

split it if you value your sanity, and clean code

#

ideally your script should only take care of 1 thing and do it well.

cosmic rain
#

I'd say depends on the code.

rigid island
#

well they mentioned movement vs interactions, something you def don't want mixed

#

I can disable interactions or movement without affecting the other, thats a win win situation

cosmic rain
#

If the movement is just setting a destination on a navmesh agent, there's not much to move to a separate script.

#

For example.

rigid island
#

even so I'd keep it in its own script but thats just my preference

#

I rather have a Movement script where i know its just that rather than scouting a movement script to find some interaction logic

vagrant oasis
rigid island
#

I started with monoliths myself ๐Ÿ˜…

vagrant oasis
#

okay thanks ๐Ÿ‘

rigid island
#

I think with time you appreciate value of non-monliths

cosmic rain
#

In my current project, I have a crpg like characters, so a lot of actions are implemented as separate classes. The character script executes the actions queue state machine and has some basic methods for controlling the characters from these actions.

#

In this scenario it doesn't feel right to separate movement into a separate script. At least not for me.

rigid island
#

yeah that specific example does make sense if thats your system, def agree where you should be aware of your setup and use what works best for your own system

cosmic rain
#

Maybe later on I'll split it if I plan on having immovable characters, though, I can just as well disable the logic itself. We'll see.

rigid island
#

yeah statemachines are tricky to split for me cause so much is kinda tied together

#

i still use enums to make my state machines , I haven't dived into the classic pattern yet tbh

cosmic rain
#

Yeah, my system is a bit more involved. It would be a spaghetti mess if I were to put all the actions in one class.

rigid island
#

jittery in what way ?

#

wait is the background a rigidbody ? ๐Ÿค”

#

for 2D ? are you sure its not just artifacts from missing pixel perfect ?

#

do you have interpolation turned on ?

#

should be yea

#

maybe show a vid what it looks like ?

rigid island
#

not entirely sure I don't do 2D much, it might be the camera. If you're using cinemachine maybe try another update mode

chrome trail
#

In the new Unity input system exactly what triggers the canceled event for a 3d composite binding? I was hoping it would just be if one of the keys was released, but that appears to not be it.

rapid radish
#

Naming convention question.

Is there a standard practice for how to capitalize tags and game objects?

Such as:
EnemyLaser
enemyLaser
enemy_laser

I'm trying to establish good habits so things are easy for future possible collaboration ๐Ÿ™‚

steady moat
vestal arch
thin aurora
#

Especially keys and names, these always use PascalCase

#

But like with all things, do what you feel fits best (tm)

vestal arch
wheat cargo
#

What is the recommended way to have a parent RectTransform conform to the height of it's child, specifically layout groups?

rapid radish
thin aurora
mossy snow
rapid radish
thin aurora
#

"Magic string" or "Magic number" is a term used for a string or number which has no specific restrictions to it, so when you make code that uses these and they exist on multiple places, they are very prone to mistakes

#

For example, missing capitalization, specifying 5 instead of 6, so you should use enums or constants

wheat cargo
mossy snow
#

do you have a warning in the content size fitter inspector? putting it on a RectTransform that has its dimensions controlled by something else is a mistake I see a lot

wheat cargo
rapid radish
thin aurora
#

So like a variable, reusing it

#

It's just that you can be sure this is the string, and it will not be changed

#

FYI this does mean you have to set the tag of things through a script, and not from the inspector

#

But I'd argue relying on inspector data is a bad habit due to how easy it can change

wheat cargo
#

I want my sub layout group's preferred height to define the height of the parent layout group

mossy snow
#

or the parent driver of your ContentSizeFitter RT can force expand horizontally if it only has this one child

wheat cargo
mossy snow
#

you are using it only to propagate the preferred size upwards, since it can't control its own layout

#

its parent is controlling its size. You just need it to let that parent know what size it wants to be

#

the other option is to change your layout such that it can control its own size, and then you can use a content size fitter there as you wanted

wheat cargo
mossy snow
wheat cargo
#

Okay I got it, I needed to have control child size on the parent VerticalLayoutGroup.
It makes sense to me now, The child group feeds the preffered size and then the parent layout group actually sets it

#

Ty

jovial barn
#

Iโ€™m on phone so I had to really zoom in cause I can barely notice the jitter

vestal arch
#

have you tried smoothing the camera?

#

my point still stands

#

yeah

jovial barn
#

I have a crazy idea what if you multiply by time.deltatime instead of fixeddeltatime

vestal arch
#

FixedUpdate happens with a different rate to Update
deltaTime is the time between calls for Update
fixedDeltaTime is the time between calls for FixedUpdate

jovial barn
vestal arch
#

well, apparently

Time.deltaTime

When this is called from inside MonoBehaviour.FixedUpdate, it returns Time.fixedDeltaTime.

jovial barn
#

So ??? Maybe thereโ€™s something there

vestal arch
#

so no, there's no difference

jovial barn
#

Bruh I did not know that

#

You learn something new everyday

vestal arch
jovial barn
#

Thatโ€™s weird that normalizing the movement vector makes it worse

#

Is the player object the only thing in the cinemachine follow

#

And look at group is empty

#

Idk I havenโ€™t worked with that

vestal arch
#

well, try disabling it i guess?

jovial barn
#

Tbh I still barely see any jitter in the video

#

If anything it looks like itโ€™s part of the pixel art aesthetic

#

Now I see it a little bit in the bottle

#

It looks correct

#

Have tried disabling pixel perfect?

#

I donโ€™t know. Unfortunately I am very bad at camera stuff and also often get camera jittery issues with my own projects

tawdry jasper
#

There is a post on unity forums saying that these 2 lines give different result:
transform.position = newWorldPosition
transform.localPosition = transform.InverseTransformPoint(newWorldPosition)

shouldn't the transform end up in the same place?

gray mural
#

It's also about performance, since it's probable that localPosition sets the position to the translated with the TransformPoint method value

#

Although the source code is decompiled

blazing tiger
#

Is it possible to extend Unity's built in classes like Vector3?

#

I'd like to add a constructor for Vector3 from int3 cause it's apparently not a thing

rigid island
#

just make an extension method sure

gray mural
blazing tiger
#

Yeah I don't think it's possible to extend constructors

gray mural
#

Without modifying the source code, yes

blazing tiger
#

Kinda annoying they never included any conversions but then again, int3 from mathematics package was probably made as a whole separate thing

gray mural
#

Although it's possible if the struct or class is partial

blazing tiger
#

You know actually I'll just make my own int3

#

And make it convertible to v3

gray mural
blazing tiger
#

Oh wait, there's Vector3Int

gray mural
#

Meaning you should be able to add a new part to it

blazing tiger
#

Man, so many data types

#

Actually int3 is also partial I just noticed

gray mural
blazing tiger
#

You can directly cast Vector3Int to Vector3 though, which is kinda what I need

gray mural
#

Right, can only be done via Vector3Int.RountToInt in the opposite direction

blazing tiger
#

Yeah I think int3 was mande as an unmanaged data type for burts and such, you'd actually want to use Vector3Int for integer vectors in managed context probably

blazing tiger
#

Ah, the opposite direction right

ionic grove
#

Hey everyone! I'm starting a multiplayer project and everything seems to working except when I spawn in a client, they aren't able to move. It just jitters. Any ideas?

EDIT: I'm using Unity 6 and Netcode for GameObjects

lean sail
violet nymph
#

Hello, I'm unsure where I should put this question, so I think general would be best for it as I don't know, anyway, onto the question:

I'm trying to get the rotation of a hit point through a raycast, my ray reflects correctly, but I'm unsure how exactly I can get the rotation from the ray reflection, I draw rays to debug it to know it was reflecting right, it seems to reflect right, but I just don't know how to get the actual rotation of what I hit and then apply that rotation to a transform (in this case just transform as it's attached to the object)

void FixedUpdate() 
{
    if (AutoAdjustRotation)
    {
        Ray ray = new Ray(Base.transform.position, Vector3.down);
        Debug.DrawRay(ray.origin, ray.direction * 50, Color.red);

        if (Physics.Raycast(ray, out RaycastHit hit, 50, mask))
        {
            Vector3 surfaceNormal = hit.normal;
            Vector3 reflectedVector = Vector3.Reflect(Vector3.down, surfaceNormal);

            Debug.DrawRay(hit.point, reflectedVector * 10, Color.green);

            Vector3 reflectedRayEndPoint = hit.point + reflectedVector * 10;
            Debug.DrawLine(hit.point, reflectedRayEndPoint, Color.blue);

            Quaternion rotation = Quaternion.FromToRotation(Vector3.down, reflectedVector);

            transform.rotation = rotation;
        }
        else
        {
            Debug.Log("No hit detected.");
        }
    }
}

This isn't my whole code, just the part that is needed in this context (There is no code aside from it causing issues)

tawdry jasper
# gray mural Since the `InverseTransformPoint` method translates the world position into the ...

I kept getting questionable results so added indicator game objects and actually trying to position to game objects, one assigning it a local inverse world position and the other one assigning a world position directly - they end up in different spots:

      var world = carryablePivot.position + offset;
        indicator.SetParent(carryablePivot.parent, true);
        indicator.localPosition = Vector3.zero;
        indicator.localPosition = carryablePivot.InverseTransformPoint(world);
        indicator2.SetParent(null);
        indicator2.position = world;
        indicator.rotation = Quaternion.LookRotation(offset);
        indicator2.rotation = Quaternion.LookRotation(offset);
        Debug.Break();

(assigning Vector3.zero) doesn't change anything, and while the indicator transforms are top level (or at least their parent has an identity / zero transform), the carryablePivot is nested in the hierarchy - which somehow influences the inversetransformpoint?

lean sail
violet nymph
short quiver
#

I have a float, and I want to check if it's >= some value. I'm aware of Mathf.Approximately - is there anything I can/should do with a >= comparison for floats?

violet nymph
#

Just random values

short quiver
#

eh, okay, fair enough, thanks

#

yeah idk why I was overthinking that so hard

violet nymph
#

Yeah, happens quite often in coding when there is a very simple solution it's thought that isn't right ๐Ÿ˜ญ

violet nymph
#

The actual rotation is 32.713, so it's not getting the rotation correctly, and I am confused as I've never used LookRotation

fallow quartz
#

I have a question regarding update and fixedupdate. You are supposed to put everything about physics in fixedupdate, but my question is, if I have a method with logic - physics logic - more logic how can i split it so everything goes to the corresponding update? Also, another problem is that fixedupdate goes before update so if the physics logic is in the middle or at the end is going to be a problem

violet nymph
#

It might be due to the += position, try using Vector2.Lerp for smooth positions

#

Or Vector3

#

Either one for whatever you are making

latent latch
violet nymph
#

It should work that way

latent latch
#

Anything that says rigidbody goes into fixedupdate. Now, input on the other hand can be placed into update, but that requires a little more setup of polling it and then checking it again in fixedupdate.

fallow quartz
lucid ridge
#

Anyone can review this code ? I just want an opinion to know if im wrong and need to use another way

fallow quartz
#

like how can I split code into fixed and update and having track on both executing like if it was only 1 method? Also fixed always executes first, but if i need it to execute it last or in the middle what should i do

fallow quartz
latent latch
#

Both, moveplayer and jump methods should be called from fixed update from what is shown there.

fallow quartz
violet nymph
#

๐Ÿ˜ญ I know fixed is for physics only, but you asked how to run them in fixed update with separate methods so I told you just run the methods inside fixed update

latent latch
#

Right, but most from what I'm seeing there isn't that frame dependent beyond maybe preventing the audio from overlapping which should be handled with additonal checks.

fallow quartz
violet nymph
#

... I helped you and you ignored me ๐Ÿ˜ญ

broken lynx
#

!code

latent latch
#

What I throw into my updates is usually just input if I am using Unity's rigidbodies. CharacterBody on the otherhand is specifically ran with update.

tawny elkBOT
tawdry jasper
lean sail
fallow quartz
#

Also, this doesnt solve the execute order problem

latent latch
#

Like I was saying, if you want to split something up there it could be input as that should be polled on a non-fixed update (even though documentation does do it)

#

everythign else there seems fine to me, and like I was saying if you aren't sure of the correct update, you're less likely to have problems sticking it into the physics.

naive swallow
#

Is there any way I can make a variable in the inspector that you can drag a Script to? Not an instance, but the script itself, to use as a type for a Generic function? If I have a MonoBehaviour that calls SomeFunction<DataType>() where DataType : AbstractDataType, is there any way I can let a user define what DataType to use via the inspector? Ideally, they could just drag in a script that inherits from that AbstractDataType into a variable in the inspector, but I am open to other solutions I haven't thought of

latent latch
#

It's better to be correct with the physics than running into problems later because you're doing something in update you aren't supposed to.

fallow quartz
violet nymph
#

To be more clear, It doesn't rotate where it should, only goes on Z (the transform I want to rotate based on the surface) to 0 when the surface is below 0 degrees on the X axis, and the transform goes to -180 on the z when the surfaces X axis goes above 0 degrees

latent latch
#

Unless you have a specific question on what needs to be executed in a orderly fashion.

lean sail
violet nymph
#

If there wasn't any clear changes I would use Debug.Log

#

Anyway, i'll try that

lean sail
latent latch
violet nymph
fallow quartz
latent latch
naive swallow
# latent latch Not too sure what you mean but not an instance when plugging into the editor, bu...

Making an extensible asset, the component in the scene is going to add a component that extends an abstract class to objects it generates. The idea being, a user would create a script that implements an abstract class in the asset, then drop the ready-made "Initializer" prefab into their scene and assign that newly-made script to it in the inspector.

There aren't any specific instances of AbstractDataType in the scene or in any prefabs, but I want the user to define which one gets passed to AddComponent later in the code

worn star
#

uh so delegates seem like array of methods , is it actually like that

naive swallow
latent latch
naive swallow
latent latch
#

for something that doesn't require editor scripting

lean sail
naive swallow
worn star
naive swallow
naive swallow
lean sail
latent latch
naive swallow
naive swallow
#

That'd make it pretty easy though

worn star
#

naughtyattributes ๐Ÿ’€

late lion
# naive swallow Is there any way I can make a variable in the inspector that you can drag a _Scr...

The script file assets are MonoScript (editor only type), but inherits TextAsset, which can be referenced in serialized fields. I can't say for certain that the references will be maintained in builds, but I'm fairly certain that it will. The text contents would be empty, but the name should be readable. For MonoBehaviour and ScriptableObject types, the name of the file has to match the name of the type, so you can use the asset name to search for the type. But not useful if you have multiple types with the same name under different namespaces.

fallow quartz
#

If my vs intellisense stops working after creating a new script how do i fix It?

#

I need to restart the IDE each time

rigid island
cosmic rain
tawny elkBOT
tranquil rover
#

I've also been having issues with VS intellisense breaking every time Unity recompiles. Tested in a new clean fresh project with everything up to date, and still happening. Anyone else getting this / found a solution? It's worked without issues for years and just started suddenly.

stark timber
#

I'm trying to wrap my head around how to make a Top-Down 2D Platformer in Unity. I know that it's possible since Lifeflame Compendium exists, but I don't know what the best approach would be.

latent latch
#

2D tileset is pretty good for it too

signal eagle
#

Can someone please tell me where I can open my project?

lean sail
signal eagle
lean sail
warped phoenix
#

with unity netcode, and animations, would it be better to :

#1 Just fire the animation on the host system that moves a gameobject, and then have the animator component disabled on the other systems, and have them follow the host movement via network transforms?

or #2 run the animation on all systems at the exact same time with rpc methods?

nova raptor
#

yo! i need to have a dictionary of a class with any type. (like, i should be able to put EventProperty<string>, EventProperty<float>, EventProperty<Vector3>, etc)

I don't exactly know what to do here, or even how to putthis into words for a google search. does anyone know how I can do this?

public class EventProperty<T>
{
    public string propertyName = "";
    public string displayName = "";
    public T value;

    public EventProperty(string name, T defaultValue, string displayName = null)
    {
        propertyName = name;
        this.displayName = displayName ?? name;
        value = defaultValue;
    }
    
}
public Dictionary<string, EventProperty<ANY TYPE> properties = new();
#

i would prefer to not use any sort of casting, since ideally an EventProperty<> can be ANY type

stark timber
latent latch
#

y sorting?

stark timber
#

If the character were to jump onto the tile, they should be put in front of it.

chilly surge
nova raptor
#

I'm making a rhythm game with a level editor, and each event can have properties (for example, a Move Character event can have a vector3 destination property)

From the dictionary of properties (the key is just the propertyName of the property), i'll use that to create fields to edit the property value (for example, if theres a Color property in the dictionary, the level editor will intantiate a color picker in the property editor)

#

All events are made from my Event class

public class Event
{
    public string displayName = "";

    public EventCallback function = delegate { };
    public EventCallback preFunction = delegate { };
    public float preFunctionLength = 2.0f;
    public int priority = 0;

    public bool sceneEvent = false;

    public Dictionary<string, EventProperty<ANY TYPE>> properties = new();


    public Event(EventCallback function = null, EventCallback preFunction = null, float preFunctionLength = 2.0f, int priority = 0, bool sceneEvent = false, string displayName = null, List<EventProperty<ANY TYPE>> propertyList = null)
    {
        this.displayName = displayName ?? "Unnamed Event";
        this.function = function ?? delegate { };
        this.preFunction = preFunction ?? delegate { };
        this.preFunctionLength = preFunctionLength;
        this.priority = priority;
        this.sceneEvent = sceneEvent;

        if (propertyList != null)
        {
            foreach (EventProperty<ANY TYPE> property in propertyList)
            {
                properties.Add(property.propertyName, property);
            }
        }
    }

}
chilly surge
#

There's not really a way to make it type safe. You have to cast at some point.

nova raptor
#

ah.

chilly surge
#

Think about it this way: there is no relationship between they key and the value in your properties

chilly surge
#

You can have unsafe write but still safe usage, depending on what you are trying to do.

nova raptor
#

oh, well i haven't done it yet lol

#

i'd probably do something like

foreach (KeyValuePair<string, EventProperty<ANY TYPE> kvp in event.properties)
{
    // first argument is the name of the property to save it in dynamicData, second is the property reference for making the type of editor, showing the value and display name, etc)
    PropertyEditor.ShowProperty(kvp.key, kvp.value);
}
#

where PropertyEditor.ShowProperty() is a function that instantiates the property fields in the property editor

chilly surge
#

I'm asking because if your usage does not need to care about the specific type, eg if you just need to grab a property from properties and then .ToString() it or something, then a common pattern is to have a non generic base below the generic version:

class EventProperty
{
    // Shared code that does not need to know the type
}

class EventProperty<T> : EventProperty
{
    // Code that does need to know the type
}

And your properties can then simply be Dictionary<string, EventProperty>.

nova raptor
#

I'll need to know the specific type eventually for instantiating (for example, it needs to know its a Vector3 so it makes 3 fields for the property, or a Color so it makes a color picker)

#

which will likely happen in PropertyEditor.ShowProperty

chilly surge
#

You can do pattern matching inside the PropertyEditor.ShowProperty method.

#

The point is that the place where you access properties, does not need to know the specific type.

nova raptor
#

thats correct

#
public class EventPropertyBase
{
    public string propertyName = "";
    public string displayName = "";
}

public class EventProperty<T> : EventPropertyBase
{
    public T value;

    public EventProperty(string name, T defaultValue, string displayName = null)
    {
        propertyName = name;
        this.displayName = displayName ?? name;
        value = defaultValue;
    }
}
#

so something like this?

public Dictionary<string, EventPropertyBase> properties = new();
chilly surge
#

Sure.

#

And instead of doing pattern matching on an unknown EventPropertyBase inside of PropertyEditor.ShowProperty(), you can make the EventPropertyBase have a ShowEditorProperty() method and you just call that.

nova raptor
#

oh, smart!

#

how would I access the EventProperty<T>? wouldnt getting a dictionary value just return the base part of it?

chilly surge
#

Didn't you say you don't need to?

nova raptor
#

i'd need to get to it eventually to change/save the value

chilly surge
#

Similar to how EventPropertyBase can have a ShowEditorProperty() method which means you no longer need to know the concrete type in order to show editor property, you can also have a Save() method.

nova raptor
#

actually, i'm a bit confused about that too; the base still wouldn't have any information about the type of the property, right? how would it know what type of property edit fields to make?

clever lagoon
nova raptor
chilly surge
#

Inherited classes can override method of the base class.

nova raptor
#

OH

chilly surge
#

You probably wouldn't use a generic, and just have EventProperty (the base class), EventPropertyInt : EventProperty (which overwrites base class' ShowEditorProperty() to show an int field), EventPropertyString : EventProperty, etc.

nova raptor
# chilly surge Inherited classes can override method of the base class.

so i would do something like this

public class EventPropertyBase
{
    public string propertyName = "";
    public string displayName = "";

    public virtual void ShowEditorProperty(){}
}

public class EventProperty<T> : EventPropertyBase
{
    public T value;

    public EventProperty(string name, T defaultValue, string displayName = null)
    {
        propertyName = name;
        this.displayName = displayName ?? name;
        value = defaultValue;
    }

    public override void ShowEditorProperty()
    {
        //stuff here
    }
}
nova raptor
nova raptor
#

and ShowEditorProperty() would do the overridden one if i call it, right? adding the EventProperty<T> to the dictionary won't just throw away the EventProperty<T> stuff (including the override)?

chilly surge
#

Correct.

nova raptor
#

awesome! thank you so much for your help tonight ๐Ÿ™

nova leaf
#

hey i was trying to create a minimap with 2 cameras (render texture and camera for it) and now i am trying to create a fov viewport box to show what the camera can see of the minimap like in an rts. i can't raycast because the game is in space (homeworld kind of game) with no ground

  • my code doesn't work properly because the fov box doesn't scale with the camera zooming in and out (y position changing) and idk how to get it working, i can't think anymore... maybe it's simple but my brain melted
    https://hastebin.com/share/ulejuhapug.java
unborn elm
#

How do you handle an override where you have three classes that inherites and want to use each others base, basicly want to use both parents and grandparents base:

public class A
{
  public virtual void Func()
  {
    Debug.Log("A");
  }
}
public class B:A
{
  public override void Func()
  {
    base.Func();
    Debug.Log(B);
  }
}
Public class C:B
{
  Public ???? void Func()
  {
    ????
  } 
}
lean sail
#

The exact code from B should work fine in C

civic girder
#

What's the consensus regarding UI in unity?
I'm making a menu based game (think rpg), so I expect the user to be able to pick moves/item/etc.

I'm not looking for styling advice, I'm more concerned about if there is a dynamic method to populate a unit's moves/item/etc into similarly scripted menus at run-time.

There seems to be a lot of ways on youtube and some of them just don't really make sense in a real-world project. (as in it's fine for the example but not really scalable or dynamic)

Any recommendations or links to learn more about this would be greatly appreciated.

mossy snow
#

Your question is so vague, it can't be answered. You can dynamically add UI items. Do this in a system that scales the way you want, I guess?

civic girder
#

okay, let me rephrase

#

I'm looking for a "clean" way to dynamically manage adding/removing UI items from menus on a regular basis with the least amount of spaghetti possible.

mossy snow
#

So make a class that dynamically manages add/removing UI items from a menu (maybe more than one class if there are different menus), but write them with the least amount of spaghetti possible... Your question is still super vague, the only thing that comes to mind is don't have menus add themselves directly to their parent RectTransforms, and that if you use GetChild or Find in any of your menu code, you failed the task

mossy snow
#

define your requirements so you can get better advice by defining things like: how many separate ui items are there? Are they defined by the characters? Can you generate them ahead of time and just disable the ones you don't need? Do they need to be updated realtime? How complicated are they? Do they need to control their layout? Are they simple "event" type actions or can they have submenus themselves?

#

most of the tutorials you find are going to be toy examples because it can become a complicated problem that's really specific to your use case

unborn elm
#

Thanks it turned out that the fact that I had it private on C while doing proteced on A & B caused the error

#

Just me not reading the error message very well

placid edge
#

Hello, I got a problem I can't for the life of me figure out, I'm trying to do a Vampire survivors clone, and I can't seem to figure out how to make enemies crowd around the player (For when the player is overwhelmed) without the enemies influencing each other's velocity.

For example if there's more enemies to the left than to the right of the player(As they're already crowding on and around the player), the overall crowd of enemies will start pushing themselves to the right due to the majority of them pushing in that direction.

Is there a way I can simply make the enemy move towards the player but not influence the velocity or push other items(or enemies), while still stopping if they come in contact with them?

#

I hope I explained that correctly...

stone pewter
#

this is like a whole ass research topic

#

I'd start by looking into crowd simulations/pathing for RTS games

#

and see how they solve it there

true flower
#

Can I make and run unit tests without assembly definitions?

somber nacelle
#

no, unity's testing framework requires them

true flower
#

โ˜ ๏ธ

swift aspen
#

what's wrong with using asmdef in your case?

#

you can just make a root catch all assembly if you don't wanna interface with it a lot

somber nacelle
somber nacelle
#

you should really give the docs a read

thin aurora
# true flower why

Reads the docs that are mentioned about how to reference TMPro. Hint: it has its own assembly definition

true flower
#

Yeah, I did this and it worked, just have to do too much to simply run unit tests...

inner shuttle
#

does the Enum.GetValues method return an array of integers?

somber nacelle
#

no it returns an Array object which will be an array of System.Object. but each object in the array will be one of the enum's values which can be cast to int if that is what you need

#

actually scratch that first part, the array will not be of System.Object, the Array object returned will actually just be an array of your enum type. just returned as an Array

thin aurora
#

There's a generic overload that returns an array of the given generic type.

#

@inner shuttle check the docs and it will be explained in detail

inner shuttle
#

yeah its fine i got it

slow crystal
#

quick question does anyone knows where i can find a trained version of the ml-agents Soccers Two

somber nacelle
thin aurora
#

Nvm then

faint tree
#

anyone use steam in their game? im having this problem where SteamClient.isValid becomes false sometimes

mellow hill
# civic girder What's the consensus regarding UI in unity? I'm making a menu based game (think ...

This depends largely on what your requirements are and what UI framework/solution you are using but if I were you, I would probably look into the MVP (Model-View-Presenter) pattern. There is a lot of information about this pattern and some Unity-implementations as well, this will ensure that your UI (View) is separate from the data (Model) and they communication via a Controller/Presenter. Once you have this type of structure in place, you can expose events to switch between presenters and this should update the view as well. Maybe you could have a Stack<T> of presenters or a way to inject them when needed (if using some DI/IoC framework) but this will help keep your UI clean but also able to switch it out at runtime (however you choose to do this depends on your requirements and architecture). Here is an article that goes over how to implement MVC/P in Unity: https://unity.com/how-to/build-modular-codebase-mvc-and-mvp-programming-patterns

#

@civic girder There is also a good video on the topic that shows how to implement this type of pattern for UI: https://www.youtube.com/watch?v=v2c589RaiwY

Demystify MVP and MVC Architecture for Unity in simple terms focusing on the Separation of Concerns and a practical example building an MMO style hotbar using a Model, View and Controller.

๐Ÿ”” Subscribe for more Unity Tutorials https://youtube.com/@git-amend

Discord: https://discord.gg/FDRZGQBBUC

#unity3d #gamedev #indiedev

โ–ฌ Contents of this...

โ–ถ Play video
lusty rapids
#

hey, im looking to use the discord SDK for RPC, every time i have tried, if discord is not open on initialzion, the game crashes (and somehow so does the editor), and if it is open and it gets reloaded (ctrl+r), i get the error NotRunning, when i try to handle it to keep checking and update the status, it doesnt detect that its open, and keeps spamming the custom error i made

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

public class DiscordController : MonoBehaviour
{
    public Discord.Discord discord;
    private bool isConnected = false;

    // Use this for initialization
    void Start()
    {
        // Attempt to initialize the Discord SDK once
        InitializeDiscord();
    }

    private void InitializeDiscord()
    {
        if (discord != null)
        {
            Debug.Log("Discord SDK is already initialized.");
            return; // Prevent multiple initialization attempts
        }

        discord = new Discord.Discord(1299033841154920529, (System.UInt64)Discord.CreateFlags.Default);
        var activityManager = discord.GetActivityManager();
        var activity = new Discord.Activity
        {
            State = "Still Testing",
            Details = "Bigger Test"
        };

        // Update activity and handle the response
        activityManager.UpdateActivity(activity, (res) =>
        {
            if (res == Discord.Result.Ok)
            {
                isConnected = true;
                Debug.Log("Discord SDK successfully loaded!");
            }
            else
            {
                Debug.LogError("Failed to update activity: " + res);
            }
        });
    }

    // Update is called once per frame
    void Update()
    {
        if (isConnected)
        {
            try
            {
                discord.RunCallbacks();
            }
            catch (ResultException ex) when (ex.Result == Discord.Result.NotRunning)
            {
                Debug.LogWarning("Discord SDK is not running: " + ex.Message);
            }
        }
    }

    private void OnApplicationQuit()
    {
        // Clean up Discord on application quit
        if (discord != null)
        {
            discord.Dispose();
            discord = null;
        }
    }
}
civic girder
mellow hill
civic girder
#

Yeah it is a heavy UI project indeed

#

I'll look into it

#

Thanks again ๐Ÿ˜Š

mellow hill
#

No problem

inner shuttle
#

is it possible to get the start/end points of a navmeshagent's path?

#

ye it is nvm

runic kestrel
#

I have a UI that comes up when the player is looking at an object, but i want another tracking ui to come up when the object is in screen within a certain range like for instance inside the dotted lines (the normal lines is screen edge) what is a good way to go about this since it should depend on distance and also another raycast looking if somethings blocking it?

leaden ice
#

don't normalize it. Clamp it

#

movement = Vector2.ClampMagnitude(movement, 1);

#

you're clamping the final position

#

you're not clamping the input vector

#

you're doing some pixel perfect thing

#

after movement gets assigned

#

delete the if statement

#

it is not necessary

rigid island
#

diag movement goes .70 ish

#

oh I meant clamp

open plover
#

If Unityโ€™s social api is deprecated, then what to use now? (Iโ€™m specifically talking about the android google play services package from the github - it still uses the social api)

rigid island
#

they're both mag of 1 they are 0.7 together

#

I fixed this easily on new Input System by switching composite type, forgot how to do it on old input system now tbh lol

compact perch
#

omg it works

        IEnumerator MyCoroutine(int waitForSeconds)
        {
            yield return new WaitForSeconds(waitForSeconds);

            yield return true;
        }


        IEnumerator CombinedRoutine()
        {
            var list = new List<IEnumerator>();

            for(int i = 0; i < 5; i++)
            {
                var enumerator = MyCoroutine(i);
                list.Add(enumerator);
                _ = StartCoroutine(enumerator);
            }

            yield return new WaitUntil(() => list.All(x => x.Current.Equals(true)));
        }
#

game changer

rigid island
#

yield return true; ? ?

compact perch
#

yea its dirty

#

but its nice we can linq

rigid island
#

also the amount of garbage here
yield return new WaitUntil(() => list.All(x => x.Current.Equals(true)));

compact perch
#

like do list.Any instead

mossy snow
#

this code is filled with wtfs

simple egret
#

list.Any(x => !x.Current.Equals(true)), so it doesn't always have to check the whole collection, it stops at the first non-match

rigid island
#

why not just use tasks anyway

compact perch
rigid island
#

you can just TaskWaitAll

compact perch
#

yes but task have to be cancelled manually

rigid island
#

true but unity has new awaitable class you can use

#

it cleans all for you

compact perch
#

yea, didnt check these out yet, but i will. For now i just do playground around coroutines to better understand how they work

rigid island
#

yeah , did you get the new Input System

#

my script is literally this cs void OnMovement(InputValue val) { movement = val.Get<Vector2>(); }

#

my input values diagonal never output to 0.7 which is what causes slowdown moving diagonal

#

nah you don't use Update with the new Input system

#

you can but you generally use Events or Messages

#

this is using Send messages which is more or less like events
the movement action is called Movement so the method called is just OnMovement ( this is standard out the box for new input system, yes its that easy)

compact perch
#

idk if its a big deal anyways, if not used too frequently

rigid island
compact perch
#

ah okay i see

#

thx for feedback

rigid island
#

I don't do pixel clamp, but I use this in regular .velocity or whatever other style rb movement, yes I always use FixedUpdate for rbs

#

idk wat you mean by pixel perfect clamp

rigid island
#

oh idk I use cinemachine and let it take care of it, but I don't often do 2d

#

idk I haven't noticed jitter on mine

#

my game is a platformer so it doesn't snap to grid

maiden heath
#

Is it recommended to have all your inputs in one singular action map

edgy ether
#

so question. when you use Physics.OverlapSphere or Physics2D.OverlapCircle the sphere/circle that is created, is it usually a child or something or is it not parent to anything at all?

simple egret
edgy ether
#

oki dokie, thank you

#

that helps me figure out what i should do

leaden ice
inner shuttle
#

Is it possible to split a navmesh agents path corners into multiple vertexes to smooth the path out?

#

ive been googling for ages but i havent found anything on that in particular

opaque sun
#

So I upgraded my project to unity 6, and now all of a sudden some random TextMeshPro scripts have 1-6 errors each

#

Most of them are like this:

#

this is the specific script these 4 errors are in btw:

simple egret
#

Update TMP from the Package Manager, and reimport the TMP assets

opaque sun
#

Also what happened here?

simple egret
#

Yep that'll overwrite the scripts with their new versions, hopefully fixing the issues in the process

opaque sun
#

so i wouldnt see errors anymore?

simple egret
#

VSC now uses the Visual Studio package as a backend

opaque sun
simple egret
#

It's a package that should be right aside the deprecated one in the Package Manager

opaque sun
#

OH I JSUT REALIZED

simple egret
#

"Visual Studio Editor"

opaque sun
#

VISUAL STUDIO CODE AND VISUAL STUDIO ARE DIFFERENT

simple egret
#

Yup, but now both use the same Unity package to run

opaque sun
#

I dont use Visual Studio Code, I use Visual Studio 2022

simple egret
#

Oh lol

opaque sun
#

please excuse me forgetting that lol

#

first time upgrading unity in a while

simple egret
#

No worries

sterile reef
#

Hey question
i have this class DamageInfo
its is passed through OnHit() everytime an entity gets hit.
The question is, would the TryGetComponent() cause lag or other issues in my case?

#

For context im making a vampire surviror-esque game

#

so expect a lot of bullets/hits

#

๐Ÿค” maybe its better to have a field for PlayerStats and check whether its Null

modern creek
#
public class DamageInfo
{
  private PlayerStats _playerStats;

  public float GetDamage()
  {
      if (_playerStats == null)
      {
        bool didFind = TryGetComponent(out _playerStats)
        if (!didFind)
        {
          Debug.LogError("oops");
        }
      }
      // .. damage calc here ...
  }
}
#

does the tryget once instead of every time something gets hit

#

better would be to do the trygetcomponent in an awake or init, but unless you have hundreds+ of items that are all doing the tryget at once, it's probably fine

sterile reef
#

this is within the damageinfo, every possible damage source creates a new damageInfo so it would still call tryget... right?

broken lynx
#

Assets/Scripts/Gun.cs(7,35): error CS0115: 'Gun.Use()': no suitable method found to override

using System.Collections.Generic;
using UnityEngine;

public abstract class Gun : Item
{
    public abstract override void Use();

    public GameObject bulletImpactPrefab;

}
sterile reef
#

i dont think you put abstract in the void

modern creek
sterile reef
#

just override

broken lynx
#

im getting this error from my gun script but when i remove override i get more errors for other scripts and when i fix them more errors appear

sterile reef
modern creek
broken lynx
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Item : MonoBehaviour
{
    public ItemInfo itemInfo;
    public GameObject itemGameObject;

    public abstract void Use();  
}
sterile reef
#

@modern creek correct me if im wrong but you use virtual void even in abstract right?

#

i do

modern creek
#
    public abstract class Item
    {
        public abstract void Use();
    }

    public abstract class Gun : Item
    {
        // nothing required
    }

    public class MachineGun : Gun
    {
        public override void Use()
        {
            // shoot
        }
    }
#

gun doesn't need to say it requires an abstract signature for "use" - it already inherits one from item

sterile reef
modern creek
#

when you create your "real" gun class, then you have to implement use

#

virtual is different than abstract

sterile reef
#

whats the difference between the abstract and virtual void

broken lynx
# modern creek gun doesn't need to say it requires an abstract signature for "use" - it already...
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class SingleShotGun : Gun
{
    [SerializeField] Camera cam;        // The camera to shoot from
    [SerializeField] GunInfo gunInfo;    // Reference to GunInfo

    PhotonView PV;

    void Awake()
    {
        PV = GetComponent<PhotonView>();
    }

    public override void Use()
    {
        Shoot();
    }

    void Shoot()
    {
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f)); // Center of the screen
        ray.origin = cam.transform.position;

        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            hit.collider.gameObject.GetComponent<IDamageable>()?.TakeDamage(((GunInfo)itemInfo).damage);
            PV.RPC("RPC_Shoot", RpcTarget.All, hit.point, hit.normal);
        }
    }
    
    [PunRPC]
    void RPC_Shoot(Vector3 hitPosition, Vector3 hitNormal)
    {
        Collider[] colliders = Physics.OverlapSphere(hitPosition, 0.3f);
        if (colliders.Length != 0)
        {
            GameObject bulletImpactObj = Instantiate(bulletImpactPrefab, hitPosition + hitNormal * 0.001f, Quaternion.LookRotation(hitNormal, Vector3.up) * bulletImpactPrefab.transform.rotation);
            Destroy(bulletImpactObj, 10f);
            bulletImpactObj.transform.SetParent(colliders[0].transform);
        }
    }
}
modern creek
#

!code

tawny elkBOT
sterile reef
modern creek
#

good use case is .. abstract is for members that make no sense unless implemented... virtual is for members that are usually the same but can be overridden

sterile reef
#

i see i see

sterile reef
modern creek
#

Example: I have a tile game like 2048. Everything's a tile:

public abstract class TfeTile
{
    public abstract int MoveSpeed { get; } // makes no sense in the abstract - every tile must define a move speed
    public int Id { get; set; } // doesn't require implementation - it's the same for everything
}
public class TfeNumberTile : TfeTile, IMergeable
{
    public override int MoveSpeed => ITfeTile.MovesInfinitely;
}
public class TfeSnailTile : TfeTile
{
    public override int MoveSpeed => TileType switch
    {
        ForegroundTileType.Snail1 => 1,
        _ => throw new ArgumentException($"Invalid tile type for snail tile: {TileType}"),
    };
}
lean sail
modern creek
#

I'd probably have guns be their own thing (and not derive from item)

sterile reef
modern creek
#

but that's just sorta how i think of things, depends on what the game is, how your world is structured, etc

#

because guns have all kinds of unique behaviour.. reload, aim, enable safety, fire secondary mode, etc

#

abstract classes can't be instantiated - they're abstract

lean sail
broken lynx
#

Im lost now

modern creek
#

in this case, there's no such thing as Gun - there's only a MachineGun which is a type of Gun (and so shares all the details described in gun)

modern creek
# broken lynx Im lost now

inheritance is hard, but ... you'll need to learn it, probably, if you want to do it right.. it's why computer science degrees exist ๐Ÿ™‚

#

But if it's confusing you, there's no problem with just making a class for each type of gun and just copying and pasting code

broken lynx
#

im still in school lol

modern creek
#

ie, do away with all of abstract/virtual

broken lynx
#

currently in yer 10

modern creek
#

you'll start to find out why you'll need it in time

broken lynx
#

learning unity for IT

sterile reef
#

๐Ÿ˜ญ

modern creek
#

it's good to learn multiple languages tbh

#

so you can see why one language does things one way, or what aspects of a language you like or don't

#

c# is king though ๐Ÿ˜‰

sterile reef
#

ikr

#

i already have an IT graduation in mostly c# and im going for that higher education one

broken lynx
#

@modern creek so u reckon the best option is to remove override and go through all the errors it gives me

modern creek
# broken lynx Im lost now

Here's another example from a different game. In this game, there are Entities - they have things like health, location. The abstract class I've made is called EntityBehaviour. There's no such thing as an EntityBehaviour by itself - only a derived class like "Engineer" or "Commander" or something.

broken lynx
#

if this helps its a multiplayer fps game

modern creek
#
    public abstract class EntityBehaviour
    {
        public abstract int StartingHealth { get; }
        public virtual int CurrentHealth { get; set; }
        public virtual void Initialize()
        {
            CurrentHealth = StartingHealth;
        }
    }
    public class CommanderBehaviour : EntityBehaviour
    {
        public override int StartingHealth => 6;
    }
#

note - abstract starting health but virtual "current" health

#

the commander doesn't need to "implement" (or "derive" this integer - it's the same for everyone - ie, it's set to the starting health)

#

that being said, there's no "default" starting health.. since every entity is different.. so that data point must be overridden in the child class

#

the reason to do this is that you can always perform entity-specific code on a commander (or anything that inherits from entity)

#

ie:

#
// kaboom
foreach (EntityBehaviour ent in AllEntitiesList)
{
  ent.CurrentHealth -= 5; // everyone takes damage
}
sterile reef
#

@lean sail the thing now is that when the hit is registered and the DamageInfo is created i still have to call a GetComponent()

modern creek
#

@sterile reef What you really want is a "model" for your player - google up "plain old class objects" or "data access object"

#

You'd then have your game object rendered by a class that handles rendering, but has a reference to the player in question

sterile reef
#

(or player depending on whos hitting who)

modern creek
#
public struct PlayerData // not a MB or GO
{
  public int Health {get; set;}
}

public class PlayerRenderer
{
  private PlayerData _playerData;
  public void Initialize(PlayerData player) => _playerData = player;
  private void Update()
  {
    /// show their HP somehow
    MyTextComponent.text = _playerData.Health.ToString();
  }
}
lean sail
sterile reef
#

oh yeah true

signal eagle
#

Is this a issue because Iโ€™m trying to get my characters camera to move, but it says this thing in the bottom left of my screen thatโ€™s all in red

leaden ice
#

You should open the console window

#

To see your errors and logs

#

It's basically telling you exactly what the problem is

#

You didn't assign a variable that you're trying to use

signal eagle
#

How do you assign a variable?

naive swallow
spare dome
signal eagle
#

I mean, Drag

naive swallow
spare dome
#

click on your gameobject that has the script, you should see a missing field in where your groundcheck variable is, you need to literally drag and drop an object from the heirarachy to that field, supposedly a "groundcheck" object which you should have

signal eagle
#

I thought that was what it is. I just donโ€™t have to drag and drop it. I just have to press on it.

#

But now itโ€™s showing a yellow bug

spare dome
#

a warning?

signal eagle
naive swallow
spare dome
#

yes so a warning, they are not errors and will let everything compile but they will tell you useful information

signal eagle
naive swallow
#

A computer that can take screenshots

signal eagle
naive swallow
#

These aren't screenshots

signal eagle
#

Then where are they are shots? ๐Ÿ’€

lean sail
#

People will very quickly stop helping if you wanna insist on sharing things in a worse way. No one wants to read bad quality images and fight to help you

signal eagle
spare dome
#

I don't know what that is, if I'm being honest

signal eagle
signal eagle
spare dome
#

bawsi and digi are correct though

eager yacht
#

Win+Shift+S the region, Ctrl+V in discord, literally done

signal eagle
#

Ok I have discord on my phone, not my computer

spare dome
#

I just use it in the browser

#

you don't necessarily need the app

signal eagle
#

Iโ€™m doing the release thing hopefully it doesnโ€™t do some bad crap

#

It said to release ?????

#

Oh my God, it works finally after hours of painful smashing my keyboard JK it works!,!

spare dome
signal eagle
#

Now I just have to repeat that painful cycle, but this time make it so my character can move

signal eagle
nova raptor
#

yo, i'm back! i need to put these EventPropertyValues in a List. They need to work as ANY TYPE (like EventPropertyValue<string> or EventPropertyValue<int>, so I have it wrapped in a typeless class that i can put as the type for the list. this works, but unlike last time, there's a problem. i need to be able to access the value, which I can't figure out how to do. does anyone have any solutions?

public class EventPropertyValueBase
{
    public virtual void GetValue()
    {
        Debug.LogWarning($"Can't get a value because there's no type!");
    }
}

public class EventPropertyValue<T> : EventPropertyValueBase
{
    T value;
    public override T GetValue()
    {
        return value;
    }

    public EventPropertyValue(T value)
    {
        this.value = value;
    }
}
#

oh hi again lol

chilly surge
#

You can return a value like object but, why do you need to access the value?

lean sail
#

generics/inheritance is specifically so you dont need to do this

naive swallow
nova raptor
#

this is for my rhythm game, specifically the chart save/load system. Theres 2 main concepts: Events and EventEntities. Events are reusable objects that don't change; they contain stuff like the function delegate, priority, scene toggle, etc. you don't need to know what tjose are, the important thing is that every Event of the same type has the same stuff.

example:

eventDictionary.Add("pulse", new Event(PulseCharacter, propertyList: new List<EventPropertyBase>
        {
            new EventPropertyInt("charID", 0, false)
        }
        ));
#

EventEntities are like the individual instances of an event; theyre stored in a list as the level's chart, and contain stuff like the datamodel (aka the event name), beat to run the event on, and (relevant to this), a dictionary of the event's properties known as dynamicData (since each event can have different properties)

example:

new EventEntity() {
            datamodel = "pulse",
            beat = 0f,
            dynamicData =
            {
                {"length", 4f},
                {"startColor", new SerializableColor(1,1,1,1f)},
                {"endColor", new SerializableColor(1,1,1,0f)},
                {"instant", false},
            }
        },
lean sail
nova raptor
#

i'm getting there

lean sail
#

You can just state the related part, if parts of it dont relate then it's just more confusion

nova raptor
#

ah sorry

#

i thought it was important to mention i guess

#

the point is, i'm going to be making those dynamicData entries by looking at the event's properties, but i need the defaultValue to do that (and later, i'm going to need value from EventPropertyValue<T>)

#
foreach (KeyValuePair<string, EventPropertyBase> property in RhythmGameManager.eventDictionary[datamodel].properties)
        {
            dynamicData.Add(property.Key, property.Value.defaultValue);
        }
cosmic rain
nova raptor
#

couldn't i just do (val is T)? Sorry, I don't know much about is

#

since outVal isn't used

somber nacelle
#

should return outVal rather than val otherwise it will error because you can't implicitly cast object to T

chilly surge
naive swallow
naive swallow
chilly surge
#

Because I don't see how dynamicData can be type safe just like you can't make property type safe.

nova raptor
chilly surge
#

If your dynamic data is just going to do something like dynamicData.SerializeToJson(), then you can just store the properties (rather than the values), and dynamicData.SerializeToJson() simply loops through the properties and call property.SerializeToJson().

#

Basically the same idea as how you solve the property problem, have a common base to represent what you actually want to do.

nova raptor
#

actually, thats what i was planning to do (if i understand you correctly)

#

wait hold on let me think-

chilly surge
#

Don't think in terms of the implementation, think about what you want to do with dynamicData first.

nova raptor
#

okok hold on

#

i need to access the property value somehow, whether thats as an object directly in the dictionary or the value of an EventPropertyValue<T>

public void SetFlash(EventEntity entity)
    {
        float beat = entity.beat;
        float length = (float)entity.dynamicData["length"];
        Color startColor = (SerializableColor)entity.dynamicData["startColor"];
        Color endColor = (SerializableColor)entity.dynamicData["endColor"];

        flash.SetColor(beat, length, startColor, endColor);
    }
#

i think i'm confusing myself even more ๐Ÿ˜…

chilly surge
#

Have a common base class/interface that exposes Length/StartColor/etc as properties, and your dynamicData can just be that base class/interface.

#

A base class/interface is how you do "I don't need to know what it is, as long as I can use it in a certain way"

rough rock
#

Did they remove RoundToInt? All the documentation says it exists but when I go to use MathF.RoundToInt it says it doesnโ€™t exist

leaden ice
#

Not MathF

#

You want the UnityEngine one

rough rock
#

Oh wow thank you. I thought I was crazy

devout knoll
#

im having some trouble with my save system, for some reason when I save it, it duplicates the number of cubes (i.e. if there's 1, it places 2 in the save file)

    private bool isSaving;
    public void SaveGame() {
        if (!isSaving) {
            isSaving = true;
            foreach (SaveManagerInterface saveObject in saveObjects) { 
                saveObject.SaveData(ref gameData);
            }
            dataHandler.SaveToFile(gameData);
            print("save");
            isSaving = false;
        }
    public void SaveToFile(PlayerGameDataFile data) {
        string fullPath = Path.Combine(filePath, fileName);
        try {
            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
            
            string JSONDataString = JsonUtility.ToJson(data, true);

            Debug.Log(JSONDataString);
            
            try {
                File.WriteAllText(fullPath, JSONDataString);
            } catch (Exception ruhroh) {
                Debug.LogError(ruhroh);
            }

        } catch(Exception err) {
            Debug.LogError(fullPath + ", " + err);
        }
    }
high condor
#

could someone help me figure out how to make the ball not clip through the windmill

cosmic rain
high condor
#

rigidbodies of player and turbine, respectfully

#

idk if this helps

high condor
#

nvm i fixed it

devout knoll
#

The JSOn prints once though

cosmic rain
devout knoll
#

if i play again, there's 4 this time

#

it seems to grab two before somehow

cosmic rain
#

Then there's something wrong with your data. What exactly are you serializing?

devout knoll
#

all the children of a gameobject called Cubes

#

this gets added to by the player

#

i want to save these objects, however they seem to duplicate

cosmic rain
devout knoll
#
[Serializable] public class PlayerGameDataFile {
    public Dictionary<float, Color32> Colours;
    public float Cash;
    public float MaxSize;
    
    public List<Cube> Cubes; // important part!!
    public List<Machine> Machines;
    
    public PlayerGameDataFile() {
        Cash = 0;
        MaxSize = 0;
        Colours = new Dictionary<float, Color32>();
        
        Cubes = new List<Cube>();
        Machines = new List<Machine>();
        
    }
}
cosmic rain
#

Print the number of cubes in the list before saving it.

devout knoll
#

before collecting items to save, it finds one, then it collects and has two

#

it's here:

    public void SaveGame() {
        if (!isSaving) {
            isSaving = true;
            foreach (SaveManagerInterface saveObject in saveObjects) { // cubes collection
                saveObject.SaveData(ref gameData);
                print(gameData.Cubes.Count);
            }
            dataHandler.SaveToFile(gameData);
            print("save");
            isSaving = false;
        }
    }
cosmic rain
#

Well, then the issue is not with your saving system but the "collecting" logic.

devout knoll
#

sent it just now

cosmic rain
#

Where are you adding to the Cubes list?

devout knoll
#

where it says saveObject.SaveData(ref gameData)

#

-# this code is a bit convoluted i think, even for myself ._.

#

i had an idea: where upon loading, i get each item with a unique position, because no items can clip inside each other
however, if cubes data isn't overwriting which i suspect is another issue, it may not work properly

the cash and maxsize objects do overwrite, the cubes list just never overwrites i think, which sounds strange but i don't know what the issue is

cosmic rain
cosmic rain
devout knoll
cosmic rain
#

As I said multiple times, the problem is probably where you modify the list.

devout knoll
cosmic rain
devout knoll
cosmic rain
devout knoll
#

print(file.Cubes.Count)

cosmic rain
#

Where?

devout knoll
#

after the Add

#
    public void SaveData(ref PlayerGameDataFile file) {
        foreach (Transform cube in CubeParent.transform) {
            print(cube.name + ", " + cube.transform.position + ", " + cube.transform.rotation);
            
            file.Cubes.Add(new Cube(cube.name, cube.transform.position, cube.transform.rotation));
            print(file.Cubes.Count);
        }
    }
#

it prints once, but has a Count of 2

cosmic rain
#

Then the list has cubes added previously or somewhere else.

devout knoll
#

before saving data, im gonna try file.Cubes.Clear()

#

after all, it should add cubes to the list after that, so it will be empty in theory before adding

#

it works

cosmic rain
#

You were probably never clearing it, so saving multiple times would keep on adding more elements to the list.

devout knoll
#

if i remember correctly, I populated the list, then loaded data based from the list, and then appended cubes on top whenever i saved instead of clearing it

fallow quartz
#

If I configured VS Code to be my IDE when working with unity and I can autocomplete the methods but it doesnt show the descriptions, how do I fix it? Also want to change the icons from the autocomplete thing cause the default ones are kinda bad

tawny elkBOT
plucky inlet
#

Clamping the vector to 1 makes its diagonal length "shorter" then one axis. Imagine going one inch up and one inch right, the diagonal from 0 to 1,1 is not the length of 1, right?

#

yeh, but you are clamping your vector length to 1. So it will never reach 1,1

#

you should just take pen and paper and visualise it to know, what happens ๐Ÿ™‚

#

Your movement is 0.71? You are still clamping it in update

dusky lake
#

The pixel perfect clamp is not really needed unless you are working with certain stylized effects that might affect rendering

based on what I am seeing here diagonal movement should be the same speed, I would assume optical illusion

maiden heath
#

Is this good practice to use StringToHash?

cosmic rain
ruby creek
#

Hey folks
I'm doing a top down placing board, I want to move camera in XY plane. But also have a nice effect to return camera to position if you pan too much in one direction
I've kinda achived that with cinemachine virtual camera with 3d confiner
But, when I control VirtualCamera, it confines actual camera, and position of acttual Cinemachine camera is absolute, so I continue to move it infinitly in the direction
Now, I tried a fix _cinemachine.transform.position = _cinemachine.State.FinalPosition; if _confiner.CameraDisplaced(), but now it feels laggy, any ideas how to improve it?

    void Update()
    {
        if (_panAction.IsInProgress())
        {
            Debug.Log($"Raw {_cinemachine.State.RawPosition}");
            Debug.Log($"Correction {_cinemachine.State.PositionCorrection}");
            var direction = _panAction.ReadValue<Vector2>();
            Debug.Log($"Move direction {direction}");
            transform.position += Time.deltaTime * moveSpeed * new Vector3(direction.x, direction.y);
            if (_confiner.CameraWasDisplaced(_cinemachine))
            {
                Debug.Log("displaced");
                _cinemachine.transform.position = _cinemachine.State.FinalPosition;
            }
        }
    }
tardy hull
#

Hello I am looking into the Unity 6 Design Patterns demo and I always was wondering why properties are done like this:

private bool isActive
public bool IsActive => isActive;

Isn't it just cleaner to use IsActive in the first place with private set? I am not sure but I think it's something from "back in the days" where we didn't have option to separate accessors for it?

dusky lake
#
[SerializeField] private bool _isActive; // Shown in inspector but not to other classes
public bool IsActive => _isActive; // Now published to other classes
tardy hull
#

But you can publish auto-property to inspector too?

dusky lake
#

and to keep the declaration of properties to the inspector the same, regardless if you want to publish it to other classes or not you always use that method, you just omit the bottom part if you dont want to publish to other classes

#

yes but the auto properties are always also shown in code completion as they are part of that classes public properties

oblique spoke
#

I think it would be helpful to explain the practical reasons for doing things like this

dusky lake
#

if you want to show to inspector but not to other classes -> only the private property
if you want to show to both -> private property + public property

dusky lake
#

Like just cause I want to expose 15 sprite fields to the inspector i dont want other classes to show them in autocomplete (or be able to access them) all the time ๐Ÿ˜„

dusky lake
oblique spoke
#

Auto properties are with [field: SerializeField]

dusky lake
#

not shown by default* ๐Ÿ˜„

tardy hull
#

That's why I use "can" in that sentence ๐Ÿ˜›

light wraith
#

anyone know how to get the "Visual Studio For Mac" outline in the Windows version? look how beautiful this looks, compared to the bloated, messy visual studio for windows...

somber nacelle
#

visual studio for mac was actually a completely different program that was just rebranded to be called "visual studio". it's unlikely you'd be able to get the real visual studio to look like this

light wraith
#

and using code is not an option for this case...

#

I tried minimizing mine to look as debloated as possible, but it still looks wild

mellow hill
# tardy hull Hello I am looking into the Unity 6 Design Patterns demo and I always was wonder...

To add onto what has been said, creating a backing field for the property will allow you to keep that field private/local to the class. This means that if other system need a reference to "isActive", you just pass around the property instead of the field but another thing that properties allow you to do is add some sort of validation or notification to the getters/setters. So for example, in the property's setter portion, you can raise an event each time it is called/invoked. So you could have something like this:

private int age;

public int Age
{
  get {return age;}
  
  set
  { 
    if(value < 18)
    { 
      //throw exception/error 
    }
   
    RaiseAgeEvent();
  }
}
rigid island
#

this was basically a Xamarin app reskinned to look somewhat like VS

maiden heath
#

Is there a "code review" channel here?

dusky lake
maiden heath
# dusky lake You can ask in here

Its a very long script, I just wanted to post it so people can notify me if I made any errors or if I can make something more efficent

#

This is it ^

dusky lake
#

Is there any parts of it you are concerned about?

maiden heath
dusky lake
#

Anything physics related should be done in FixedUpdate

somber nacelle
#

why are there so many static variables that don't even need to be static? you just assign them in Awake regardless of whether they are already assigned

rigid island
dusky lake
#

that sounds... weird ๐Ÿ˜„

somber nacelle
#

also you use regions to separate behavior inside of a method. Split that into different methods for each type of behavior and just call those methods from Update

spare dome
maiden heath
#

Does it?

rigid island
rigid island
dusky lake
#

My bad then, never used the character controler, always just custom implementation + rigidbody and assumed it just uses physics too

rigid island
#

technically anything with a collider is a physics objects
collision = physics

spare dome
maiden heath
spare dome
#

might need to test that

maiden heath
somber nacelle
#

you can't jump if you use SimpleMove because it ignores all movement on the Y axis

rigid island
maiden heath
rigid island
#

even the manual mentiones

Velocity along the y-axis is ignored. Speed is in units/s. Gravity is automatically applied. Returns if the character is grounded. It is recommended that you make only one call to Move or SimpleMove per frame.

rigid island
#

thats because its overriding it on its own

dusky lake
#

Returns if the character is grounded
But what does it return Confused

spare dome
spare dome
#

I never use simplemove anyway, but either way that should be the only physics a CC gets

rigid island
#

I mean like I said, technically all collider objects are physics but yeah its not DYNAMIC physics

cursive coral
#

I wanna code a grapple hook mechanic. How can i do that. Its a first person platformer i wanna make.

rigid island
cursive coral
#

Should i use character controller or rigidbody

spare dome
rigid island
#

this qustion has been beaten to death

spare dome
#

its mainly up to preference

cursive coral
rigid island
#

do you want to deal with fighting the "natural" physics forces etc.

spare dome
#

if you know how to code physics and need snappy movement, sure use a CC
if you are a beginner or an expert alike, but want the physics "feel" of a RB and dont want to code physics, sure use a RB

rigid island
#

Kinematic is best for most control. Now do you want to deal with stairs on your own?
otherwise use CC (also has other benefits)

cursive coral
#

Coding your own physics sounds harder

rigid island
#

except CC already can hop step-height, kinematic rb can't

cursive coral
spare dome
#

tbf you need to code stair and slope movement for a kinematic RB

rigid island
cursive coral
#

I wish i could use both cc and rb

rigid island
#

why.. that would make no sense

#

thats like saying I want to drive a car while driving a truck

spare dome
#

jeeptruck lol

cursive coral
#

Anyway how do i code a grapple hook

spare dome
#

those exist and are abominations

rigid island
spare dome
rigid island
#

maybe just use Dynamic RB(whilst grappling ) if you plan on adding some type of "swing" otherwise you need to manually code it with Sin/Cos functions

cursive coral
cursive coral
tawny elkBOT
spare dome
rigid island
#

I personally used a Rigidbody and Spring joint

#

works well for my usecase

#

you canmake the rb swing on it and stuff

cursive coral
#

Cool.

rigid island
#

basically I shoot a ray, then the Hitpoint gets the anchor of the Spring and attach to my player rb

#

play around with the spring amount to control shrink / extending "the rope"

cursive coral
#

Do you have to point your cursor to the hook?

spare dome
#

point the cursor to the object which the "hook" will lay on? yes

rigid island
spare dome
#

only when firing it though

cursive coral
#

Also something unrelated to thiz, i am looking to learn math and physics specifically for unity gamedev where can i start

spare dome
#

well gamedev uses traditional math, you can learn how physics work by any physics textbook out there

rigid island
#

mostly trig math

rigid island
#

was hard to get a swing in that spot lol i couldve picked a better spot smh..

spare dome
#

thats terrifying that that beam can shoot through walls

cursive coral
#

Wall hax

rigid island
#

but you can see the visual so you know when not to poke your dome ๐Ÿ˜…

spare dome
#

are structs just a group of similar group of variables and can call them like such struct.VarA/B/C?

#

I'm not entirely sure if I should use them over/with classes or not

somber nacelle
#

structs are value types and (typically) live on the stack rather than the heap. they are passed by copy rather than reference

rigid island
#

structs are just like classes, except internally they are handled different

#

whenever my fields/props are mostly value types, I stick to structs are they are slightly more performant since they not need to be GC like ref type

#

one annoyance is that Unity doesn't support the latest c# so you can't initialize structs fields with values..

 public struct SomeInterestingData
 {
     public int Bleep  = 40; //not allowed
     public int Bloop;
 }```
spare dome
#

instead of Class _Class;?

rigid island
#

notice how when you change .position you have to assign a new v3

#

you can never change the original position of an object

#

you always get a copy / replace with a new struct

#

instead with transform a reference type, once you store the reference in Awake lets say.. its always the same transform

#

thats why you can't cache an objects position in awake if you want to constantly have the current value

spare dome
#

so instead of directly modifying them, it creates a copy so you modify the copy instead

rigid island
#

yea thats why you assign it back

spare dome
#

alright thanks nav and box

#

appreciate it

gritty badger
#

Yo need a little help here please.
Here is what it's supposed to happen:
the player has an empty object with a trigger that when got triggered like collides with a weapon in this case, it should made the weapon a children of the player and move along the player, like what happens after the NPC moves across the weapon. But it didn't. The NPC part works, but the player will always get nullref. I don't understand why, could someone help me?

#

please?

rigid island
gritty badger
#
    void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.tag=="supply"){
            Debug.Log("collected");
            supplt.pickup();
            picked=true;
            
        }
        else if(other.gameObject.tag=="melee weapon 1"){
            weapongrab.grab(player.transform);
        }else{
            Debug.Log("eeee");
        }
        picked=false;
    }

the part where the player got nullref, but not the NPC

spare dome
#

dont cross post

rigid island
#

you outta post the code properly @gritty badger

#

โฌ use links

tawny elkBOT
spare dome
#

stupid halloween sound, you can change it in sound settings

gritty badger
#
    void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.tag=="supply"){
            Debug.Log("collected");
            supplt.pickup();
            picked=true;
            
        }
        else if(other.gameObject.tag=="melee weapon 1"){
            weapongrab.grab(player.transform);
        }else{
            Debug.Log("eeee");
        }
        picked=false;
    }
rigid island
gritty badger
#

and the geab function

    public void grab(Transform _parent){
        knife.transform.SetParent(_parent);
        knife.transform.position=new Vector2(_parent.transform.position.x,_parent.transform.position.y-1);
    }
#

grab

rigid island
#

what are you doing my guy

spare dome
#

you just posted the same code 3 times

rigid island
#

you just ignoring what was just said

gritty badger
#

but this is different

rigid island
#

this helps nothing

#

literally

#

you have to show the script and what is LINE 23

#

the sensible thing most people do is post the entire script, properly through a link

gritty badger
#
        weapongrab=GameObject.FindGameObjectWithTag("melee weapon 1").GetComponent<weapongrabscript>();

rigid island
#

idk why you're making this fucking diffuclt

gritty badger
#

this?

#
    public weapongrabscript weapongrab;

the call part

rigid island
#

triggercollisionscript

#

post the script

#

use links.

gritty badger
#
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Scripting;
using UnityEngine;
using UnityEngine.InputSystem;
public class triggercollectscript : MonoBehaviour
{
    public GameObject player;
    public suppltscript supplt;
    public bool picked;
    public weapongrabscript weapongrab;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        supplt=GameObject.FindGameObjectWithTag("supply").GetComponent<suppltscript>();
        weapongrab=GameObject.FindGameObjectWithTag("melee weapon 1").GetComponent<weapongrabscript>();
        picked=false;
    }

    // Update is called once per frame
    void Update()
    {
        supplt=GameObject.FindGameObjectWithTag("supply").GetComponent<suppltscript>();
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.tag=="supply"){
            Debug.Log("collected");
            supplt.pickup();
            picked=true;
            
        }
        else if(other.gameObject.tag=="melee weapon 1"){
            weapongrab.grab(player.transform);
        }else{
            Debug.Log("eeee");
        }
        picked=false;
    }
}

the entirty of it

rigid island
#

this is horrid to do in Update.
supplt=GameObject.FindGameObjectWithTag("supply").GetComponent<suppltscript>();

#

jfc

#

anyway doesn't seem like a gameobject was found with that tag

knotty sun
gritty badger
#

also one player gets nullref, NPC don't.

#

I used debug.log for the else if statement

rigid island
#

why would you put that line in Start and then update

#

if line 23 is spitting error, the only thing it could be is GameObject.FindGameObjectWithTag("supply") not returning a gameobject, you can't GetComponent on a null object

#

there is absolutely no reason to even do this every frame..

#

or call that function.. if its a pickup, all is needed is grabbing that specific component on that specific object through the collider in the Physics trigger invoked

gritty badger
#

no I tried comment the line and the player can't be able to collect those supplies

young sinew
#

Anyone know how to recreate something like this, where you collect and the money size grows. I am not making this type of game but kinda want the mechanic bc it is useful for somethings

rigid island
young sinew
#

I will do something basically like that except that it will be different objects the user holds

gritty badger
#

so how do I fix it?

rigid island
gritty badger
#

you mean write the component into the trigger as a parameter?

rigid island
#
   public GameObject player;
    void  OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.TryGetComponent(out suppltscript supplt)){
       
            supplt.pickup();
            Debug.Log("collected");
        }
        else if(other.gameObject.TryGetComponent(out weapongrabscript  weapongrab)){
            weapongrab.grab(player.transform);
        }
    }```
gritty badger
#

thanks

rigid island
#

everything else can literally be deleted

tardy hull
north shore
#

does anyone know how photon fusion made their script look like this in the unity editor? i want to make something similar to that for my own scripts.

somber nacelle
cunning burrow
#

So I wanna do localization, I have a custom script that will load the text onto the text box, but more importantly I'd like to know how can I reference global names in my locale text, like places in the game or character names, and when it comes to string tables, what's the best practice? Should I have one table for every story act in my game? Can I then still reference my characters from a global string table or something, it's all a bit new to me :3

inner shuttle
#

hello, im having an issue with rotating my nav mesh agent to face a certain direction. the direction is set as the first corner of the agents next path, however sometimes it doesnt work it depends what orientation he is at the time, ive tried different types of rotating and ways of calculating the direction to face.
https://pastebin.com/s0Cs0Az2

this is what it should look like:

upper pilot
#
float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float parsedVal);

I parse a val which is 0,5 using InvariantCulture, but it returns 0.
Any ideas what is wrong with the above?

leaden ice
#

Also pretty sure invariant culture expects . as the decimal, not ,

upper pilot
#

Then which one expects , as decimal? I guess that I can just parse the string and replace , with .

knotty sun
#

lots of languages use a comma separator Spanish for one

upper pilot
#

I thought there is a generic one, but I will go with replacing , with . then.
Idk why I didn't think of that earlier lol

knotty sun
#

point is you should serialize using invarient culture then you can deserialize it using that as well

upper pilot
#

I am using Inky which returns a value based on my system settings and there is nothing I can do about that except fix it after I get the value.

knotty sun
#

problem with that is, what do you do when the users language is English?

#

you replace , with . and . with , then you have the same problem

upper pilot
#
val = val.Replace(",", ".");
#

This will replace only 1 way right?

#

I want the float to always use .

#

or rather the string which is parsed to float

leaden ice
knotty sun
#

yes and say I have 1,000.00. you end up with 1.000.00 which wont parse

upper pilot
leaden ice
#

because 0,5 uses ,

#

you said you always want to use .

upper pilot
#

yes I need to convert , to .

#

because I get , from a string

leaden ice
#

where is the string coming from

upper pilot
#

inky egine

leaden ice
#

is a player typing it in?

knotty sun
#

then that is what needs fixing

leaden ice
#

what part of inky engine is giving you a numerical string?

upper pilot
#

I cant fix it, its just going to be either , or . based on User system settings

#

Its hidde in source code, I don't know, but I can't fix it

knotty sun
#

do you have the source code

leaden ice
#

I'm trying to understand the context

upper pilot
#

I tried, I reported it to them, but it may or may not be fixed.

leaden ice
#

of why you're getting a numerical string in the first place

#

and in any case - if it's using user system settings then you could do the same

#

and parse without providing a culture

upper pilot
#
audiomusic:asset'music_prologue',loop'0',volume'0',volumeend'0,5',time'1000'

We use tags

#

volumeeend'0,5' would be volumeend'0.5' on different system

#

I get those tags from the engine at runtime

#

Let me parse without providing culture then

#

I assumed that Invariant is specifically for that purpose, but I got it wrong?

#

Float will never be 1,000.000 btw I dont know which float can have multiple separators, but we wouldnt have them

knotty sun
#

yes you did

leaden ice
knotty sun
#

all kinds of numerical and date/time data has culture related separators, you're only storing up trouble by not dealing with them correctly

upper pilot
#

Tbh I never had to deal with that issue until recently when we started to parse strings to floats.

upper pilot
#
    public static float GetParsedFloat(Dictionary<string, string> dict, string key, float defaultValue)
    {
        dict.TryGetValue(key, out string val);
        if(val != null)
        {
            float.TryParse(val, out float parsedVal);
            return parsedVal;
        }
        return defaultValue;
        //return dict.TryGetValue(key, out string val) && float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float parsedVal) ? parsedVal : defaultValue;
    }

This works, left commented code for reference

#

Thanks! No idea why I got stuck with InvariantCulture for so long tho, I need to fix the rest of my code that is parsing floats ๐Ÿ˜„

glossy harbor
#

hey! I'm currently working on this 2D point and click puzzle game and I was just curious how people handle scenes? I started by having a bunch of canvas and deactivating them and activating when need be however that didn't really feel right. So I started creating those canvas in the scene, and that works for one of the places in my game, and I know I can use the scene management library to just move the player between a new scene but I also have a lot of different data I would want to use so feels difficult if I had to do that each time a player wanted to go between two places. Just wanted to see if anyone could point me in a direction to get that figured out as I can't seem to put a label on it to research it good enough.

plucky inlet
deep oyster
#

if I've got an object with several child objects that each have their own colliders, and I want multiple of the children colliders to have their own OnTriggerEnter functions, do I need to give each of those children their own script, or can I somehow assign an OnTriggerEnter function to a collider that is not on the exact object the script is on?

hollow obsidian
#

any chance I could get some assistance on a rotation issue. I have a floating model that rotates at a fixed speed, but I have also applied a rigidbody to it where a user can spin the model with mouse input. I want it so that when torque is not being applied though, the object slowly returns to its default position and rotates as normal

lean sail
deep oyster
#

Blech. Alright.

lean sail
glossy harbor
#

Not sure what exactly you are struggling

proper pier
#

Compute shader (FFTSpectrumViewer): Can't find kernel (0) variant with keywords: CHANNEL_BLUE CHANNEL_GREEN CHANNEL_RED. Does anyone know why I'm getting this error in the snipped code (FTTSpectrumViewer) provided in the hastebin. The error comes from the dispatch line on the computer shader

hollow obsidian
# lean sail Did you try anything related to this? It's not really clear what part you strugg...

Yeah I basically have a pivot point as a parent object to a 3d model. using transform I have the pivot rotating over time which in turn viusally spins the model. The user can also use their mouse cursor to spin the object in any direction. My goal is to have a "reset" key which sets the pivot point (and in turn the model) back to its orginal position just in case the model gets all outta control. the problem is that to do the manual spin I have a rigidbody and then then constant spin is done by transform. I am confused as to how to reset both to their original position

#

maybe best if you have a moment if I dm you my code?

prime moat
#

Would a question regarding ontrigger enter and triggers go to physics or here?

dusk apex
#

If it's related to code, possibly here. If it's related to the Editor, inspector or physics engine.. probably there.

prime moat
dusk apex
#

The main difference would be that moving the Transform does teleporting whereas CC does not.

#

Maybe something is blocking you from going into the door?

#

It's rather difficult to tell what's happening from the video.

prime moat
dusk apex
#

Show the inspector for the trigger object

prime moat
dusk apex
#

Show the inspector for the Character

prime moat
dusk apex
# prime moat

I don't believe you should use CC and rigid body together like this. Consider using one or the other only?

prime moat
dusk apex
#

You'd only need a Rigid body and a collider.

prime moat
# dusk apex You'd only need a Rigid body and a collider.

The problem is i cannot use an collider in the Player as it messed up the whole FPSController and makes the player bug out of the game and fly away three times the speed of the light, so that's why i use an RigidBody instead of an collider

dusk apex
#

CC has its own physics system

prime moat
dusk apex
prime moat
lean sail
warped mason
#

i'm new to coding and unity and i'm just trying to get familiar with the syntax. in my project, i have GameObjects with colliders and one with a RigidBody2D but OnCollissionEnter2D doesn't detect any collisions

rigid island
warped mason
#

I see

#

it says

rigid island
#

oh nvm ig

#

mine does it ... weird..

warped mason
#

doesn't work

rigid island
#

also look at my screenshot, my IDE tells me whats wrong pertaining to unity

warped mason
#

i feel very stupid

#

my problem was that i spelled it "collission" and not "collision"

rigid island
#

well actually now that you pointed out thats probably why you didn't get that message

#

I'm blind ig. ๐Ÿ‘“

#

but that would still not solve your issue but your IDE should now tell you why its wrong

warped mason
#

it worked

rigid island
#

you changed the type as well?

warped mason
#
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        Debug.Log("Touched ground.");
    }
}```
rigid island
#

good good

warm cosmos
#

I'm getting the same result every time from this

#

am I missing something?

#

I don't mean the same sequence, I mean literally the same result: 2, 2, 2, 2, 2, etc.

mellow sigil
#

#๐Ÿ’ปโ”ƒcode-beginner but an int variable can only hold one number at a time. Every time you assign a new random number to it, it overwrites the previous one

warm cosmos
#

yes, and I am stepping through each line

#

this was just for debugging purposes, and the result is 2 repeatedly

#

the range is 0, 4

#

so I don't see why it is not behaving like I would expect

mellow sigil
#

Have you tried printing the values in between

warm cosmos
#

hm, so I just gave that a shot and it changes the random value now, but without the Debug.Log statement the result is always the same

mellow sigil
#

Random.Range has no side effects so it might optimize the repeat calls away if you don't do anything with the value

#

actually it does advance the rng generator so who knows, maybe debugger issue?

lean sail
#

it would affect the rng

mellow sigil
#

yeah

lean sail
#

i assume theres something else going on, where do you see this repeated value of 2? because the debug.log changes absolutely nothing

warm cosmos
#

I think it's actually just a coincidence..

#

I tried difference seeds and increased the resolution, and the behavior is what I expect

lean sail
#

if you're manually setting the seed, then the same seed will give you the same result

warm cosmos
#

yes, that part makes sense

#

but I didn't expect the sequence to be 2,2,2,2,2,2 by chance I guess

#

it's working though, thanks for the sanity check

#

it is actually random chance, I can't believe it

#

there's like 8 islands that all got the same random number

grand aurora
#

HI, guys. How can i avoid triggering OnTriggerExit() if i am still touching the same object that is close by?

dusk apex
grand aurora
#

there are wall objects that a followong each other. I want to trigger change hand animation to avoid wall clipping when i am touching a wall. So, when i don`t touch, the animation is set to normal. So when i run near walls, ontriggerexit is being called as i stopped touching the first wall. bit i am still touching the second..

latent latch
#

Some ideas is using some flag when you are touching the wall which is checked every frame. Maybe something like OnTriggerStay() instead, so perhaps a statemachine is probably how I would do it.

pastel patio
#

Hi guys, my game switches between two different input modes, but this detection always says that there's a mouse device, I'm confused why...

InputType input = InputSystem.devices.Any((InputDevice device)=>device is Mouse) ? InputType.Mouse : InputType.Touchscreen
#

Does WebGL by default always provide both?

soft shard
pastel patio
#

I'm testing the WebGL build

dusk apex
pastel patio
#

I have a hunch that it's an issue that only occurs on WebGL builds

dusk apex
#

I'd be curious to see what devices it thinks are connected UnityChanThink

pastel patio
#

Good point, worth a shot at looking at what it logs when ran in the browser

#

Previously I had the opposite issue- Touch supported is always true even if you ran it on a desktop, as long as it's in the browser