#archived-code-advanced

1 messages · Page 35 of 1

stiff hornet
#

Pretty much all Unity functions will error

#

so stuff like GetComponent

#

or properties like .name

serene pawn
stiff hornet
#

You could also try using coroutines and spread the calculation over many frames?

#

might make the game feel more responsive

serene pawn
stiff hornet
#

Unitask is a popular solution as well, can make stuff run off main thread easier (has the same function restrictions)

#
// Multithreading, run on ThreadPool under this code
    await UniTask.SwitchToThreadPool();

    /* work on ThreadPool */

    // return to MainThread(same as `ObserveOnMainThread` in UniRx)
    await UniTask.SwitchToMainThread();
serene pawn
stiff hornet
#

The job system without using Unity's ECS solution is basically good for only doing math computations off the mainthread

#

You can't send in classes only unmanaged data like structs

#

So just like the other ways you can't use Unity Engine functions from classes inside the job

#

You really do need to look into the deep profiler again

#

There's probably a lot of stuff you can optimise first

serene pawn
stiff hornet
#

Or this?

#

If you are on hierarchy view then you just click on the frame you want at the top and then can expand the stuff

#

If you are on timeline view then you get the graphical looking one built like an upside down pyramid

#

In deep profile mode you should get more layers and see what is exactly costing the most

#

I'm going off this page since i dont have Unity open rn

serene pawn
#

ok thanks! I'll see what i can find out about my methods' performance

timber flame
#

What is your way to handle it?
In my voxel game, I want to add sloped and curved surfaces if voxels are placed in specific manner.
For example, the first voxel, forward, the second right and then right-up.
forward, backward, left, right, forward-up, forward-down,left-up,left-down,...
I have encoded them.
Now, the input is a path (sequence of voxel places) and I want to instantiate the correct prefabs after deconding them.
My approach is to create a tree and its labels are prefab ids e.g.. Just, traverse the tree and if the current node is a label, instantiate the corresponding prefab and then go on from the root again.
Another way is to create a hash table/dictionary. The key is code and the value is prefab id.
Do you know any better way?

severe topaz
tender solar
#

Hello, is there a way I can have a script update even when the game isn't running? I have a script that adjusts a UI's position relative to a parent character that I'd like to be running when I'm moving characters around in edit more.

opaque wedge
#

yo, uh i got a problem with Photon Fusion, I was watching this tutorial right there : https://www.youtube.com/watch?v=hqIZCoLHOig&t=156s and as you can see, he is using a "NetworkPlayer.Local" method, and I don't have it, someone know fou why ?

In this tutorial series I'll show you how to create an online multiplayer first person shooter with Unity and Photon Fusion from scratch. Download complete Unity project 👇
https://www.patreon.com/posts/multiplayer-fps-65725126

📍 Support us on Patreon to help us make more videos like this one https://www.patreon.com/prettyflygames

In this episo...

▶ Play video
wet sail
#

Is there no way to get the Laptop's Trackpad horizontal/vertical/touches in Unity ?

gray arch
#

Hello! I hope I am right here. I need some advice please.
Id like for the players to choose an item from a dropdown list. But whatever they chose needs to have store a corresponding function. My ideas so far was to use an enum for them to pick from, and a switch case that takes their chosen item to execute the corresponding function. It is quite repetitive. Are there any better ways to approach this?

west plaza
#

Hey, happy Christmas.
I currently work with the NavMeshAgent and some collider.
My problem is, that the Agent suddenly teleports away when it collide with a collider. I use the Set destination Method, so I have no idea what the problem is.

gray arch
#

I am playing a game in which I can create my own spells. I, as a player, want to be able to choose from a dropdown list what effect my spell should have. Then I am done with creating the spell. When I cast the spell, I expect it to have the chosen effect on the target.

#

The spells effect needs to have a few bits of information: the string that is displayed in the dropdown "Heal the target by ..." , the actual information about which effect is meant , likely an enum, and the function that belongs to it to cast the spell. Maybe a data table?

#

But the main part that I am concerned about is how to store the function, access it easily

#

thank you very much, I will read that!

#

I see. Thank you for the quick input :> appreciated

#

Its a cool method for understanding the problem, definitely

tropic stag
#

I have a csharp question:
Why use the T? x = getSomething()... if (x.HasValue) { if you can do T x = getSomething.... if (x != null) { Are the 2 interchangeable?

upbeat path
jolly token
tropic stag
#

Save for native types, when I'm writing my own stuff, can you give me a good rule of thumb on when to use a Struct vs a Class for a "data type"? I feel like there's no real advantage to using a Struct (I can only think of space maybe, but then my almost-empty unity project ends up being a >50mb app on android...)

jolly token
flint geyser
#

How do I make a generic method have the same parameters as the T type's constructor?

austere jewel
flint geyser
# austere jewel You can't. I would perhaps try a different code structure, like something that u...

Here's what I'm trying to do at the moment, do you think I need to do it with func?

I'm trying to accomplish creating a method like inew<T> which will have its parameters automatically changed to match those of T's constructor's.
Than you can use another similar method which instead of creating objects of said type has properties corresponding to each of the parameters T type's constructor contains. Then you can use method Decorate on this property to create a decorator for one of the parameters. Gonna be something like ReadType<Car>().MoverProperty.DecorateWith( (x) => new MoverDecorator(x, ..., ...)).
As a result when you do inew<Car>(new SimpleMover(), windowColor) the Car you get as its mover has such an object - new MoverDecorator(new SimpleMover(), ..., ...).

austere jewel
sleek lantern
#

ive got basic modding support in my game using external code compiling and execution

#

and i need to know

#

if a player accesses an existing prefab and changes something on it, is that change then permanent? (in a build of course)

#

basically are prefab assets sandboxed in unity builds?

sleek lantern
#

so not like in the unity editor? thats what I was hoping for

lyric dragon
#

Hello guys!
I have a question for those of you who are experienced in creating architecture for the backend part of the UI.

I have several UI pages in my app, each of which collects some information from the user.
The information collected from the page_0 goes to page_1 and eventually all information has to be passed to another scene. Refer to the screenshot for the structure of my gameObjects (each representing a separate UI page)

What is the best architecture I can come up with in order to write as less code as possible, be clean and efficient?

Thanks for your time!

kind sigil
#

Editor only code, I need to iterate all my scenes, how do I check if it is already loaded? I need this check because if it hasn't been loaded, it will be unloaded when operation completes. If it has already been loaded, then it will not be unloaded.

sleek lantern
west plaza
remote drift
#

I'm looking for a way to combine OOP UI and ECS Game Model
But I can't quite figure, what pattern to use to achieve it
While UI logic can work fine with other UI logic
when it comes to ECS logic to interact with UI, I got stuck
Is there maybe any existing solutions to this, or anyone has any idea that might be useful?
Key constraint here:
Game Model is not supposed to interact directly with UI logic. It can only read/modify data, that is global (meaning can be read or modified by UI logic too)
My initial idea here: use some sort of simplified HTTP get requests, but I'm not sure if that's the way

gray arch
#

Helloo! Is there a way to make an enumerator of all public enum types?
I have three public enums and Id like to have one dropdown list to pick which enum to use

native jasper
gray arch
jolly token
gray arch
rancid swift
#

The Unity 2022.2 patchnotes include:

Scripting: Allowed you to pass additional files to the roslyn analyzer and make them part of the dependency graph.
Does anyone here know what that means exactly? I cannot find any further details via Google or the official docs 😅
I'm especially confused since I managed to pass additional files in 2022.1 already with a csc.rsp file

scenic forge
#

Currently you can pass additional files, but changes won't be picked up because Unity is not aware.

rancid swift
scenic forge
#

Not sure if there's an official way, but I personally just add it via additional compiler arguments.

rancid swift
#

That does make some sense, thanks!

scenic forge
#

I'm not sure though, just interpreting what it says, but yes that's currently one of the big pain points of using additional files with analyzer/SG so it's hopefully to address that problem.

rancid swift
#

My biggest pain point is that diagnostics aren't displayed in IDEs for some reason harold

smoky glade
#

Hi all. I have a bit of code architecture dilemma
This is actually from Fusion BR sample, but the case is general:
There's a class called NetworkGame(NG) that handles player connecting, waits some initialization from each player, and then passes to Gameplay(GP) for it to spawn the actual player character

I wanna add some login and character select, which would fit in NG, but login and chara select only happens on certain game mode, whether the session is official, etc
So i'm thinking of moving the Login and CharaSelect sections to another class. Altho these are still very tightly coupled with NG. My justification to "split" them is just bcoz Login and CharaSelect is not a code flow that always happens

thin wagon
#

Is there any way to create a persistent TransformAccessArray? I want to have my units run a boid simulation I feel that being able to Add onto my existing list rather than have to re-create the list every frame would be a huge boost to performance

modest needle
#
using Unity.Collections;
using Unity.Entities;
using Unity.Transforms;

public class MySystem : ComponentSystem
{
    private NativeArray<Transform> _transforms;
    private TransformAccessArray _transformAccessArray;

    protected override void OnCreate()
    {
        // Create the native array with the desired length
        _transforms = new NativeArray<Transform>(100, Allocator.Persistent);

        // Create the TransformAccessArray using the native array
        _transformAccessArray = new TransformAccessArray(_transforms);
    }

    protected override void OnDestroy()
    {
        // Dispose of the native array when the system is destroyed
        _transforms.Dispose();
    }

    protected override void OnUpdate()
    {
        // Use the TransformAccessArray as you would normally
        // ...
    }
}
#

@thin wagon By creating the NativeArray with the Allocator.Persistent flag, you can ensure that the native array will not be garbage collected and will remain in memory until it is explicitly disposed of. This allows you to reuse the TransformAccessArray and avoid the overhead of re-creating it every frame.

glass wagon
#

is there no way within the editor to modify the properties of added Scenes' PhysicsScenes?

sturdy fable
#

Hi. A question about using unity as library in a native Android app. I was able to make it work with a barebones unity app that does nothing, but once I added a 3rd party plugin to my unity app, I get an error when I try to build the native app: "Could not find :poseplugin:. Required by: project :app > project :unityLibrary"

Now, what should I do? Im very new to native android development, so im not sure if I should add the 3rd party library somehow to the native app or what

#

I checked that the .aar file of the plugin in question (posePlugin) is present at the unityLibrary\libs folder in the project that unity created

#

on line 6 it lists the poseplugin

#

so somehow android studio is not able to find it, although the file is present in the libs folder

finite pond
#

Changing a camera's orthographic size rebuilds the entirety of my Screen Space Camera canvases and it lags a lot. Is there any way to fix that? I cannot use overlay canvases!

merry hill
#

I'm making instances of classes using constructors and calling them with the proper parameters using Activator.CreateInstance(),
however, some child classes don't have the same parameters and instead pass default values to the parent constructor.
For example:

public class Foo
{
    public Foo(string v) { }
}
public class Bar : Foo
{
    public Bar() : base("defaultValue") { }
}```
Using Activator.CreateInstance() on this child class with the parent parameters results in an error as the parameters don't match.
Is there a way to selectively use parameters to fit the constructor? So you would pass a string and if you generate a Foo instance it uses that string, but if you generate a Bar class it drops the string to fit the constructor.
I could also make a second constructor with all parameters and just don't pass them to the parent constructor but if there is an easier way that I only have to implement once that'd be great.
pine pendant
merry hill
pine pendant
pine pendant
merry hill
#

no problem, ill figure something out

fallow sentinel
#

Hello everyone, I hope you are well!
Sorry to bother you, but I need help with physics :(
I need to add different forces to an object, but to be able to maximize the velocity that force will apply.

Basically:
A Wind script that adds a force (2,1) but will add no more than (5,5) in velocity.
A Movement script that will add a force depending on the input, but will add no more than (20,0)
A Jump script that adds an impulse force of (0,15)

Do you have any idea how to do this?

undone coral
merry hill
# undone coral what are you trying to do

say I have a class that i created using a constructor with several parameters
i would then like to create a "copy" of that class by passing those parameters again into the constructor
for that im using Activator.CreateInstance()
however, due to inheritance, some constructors use more or less parameters than their parents constructor, so when its more, i override the Activator call and call it with the correct parameters
and i could do that with less parameters too, or give them a constructor with parameters that i dont use, but i have a lot of those classes to make an override method or an additional constructor for in that case and was wondering if it is possible to just pass more parameters than needed and have it dynamically choose the constructor to fit as many parameters, and drop the ones that arent used

undone coral
#

design each layout, then design the regions of the screen where that layout should be active.

undone coral
#

if you need to copy, use a single class that can store many different kinds of data, instead of many classes each with little pieces of data

#

what are you trying to do?

#

what is this for?

#

Activator.CreateInstance()
this is a code smell. it means you are doing something wrong

fallow sentinel
# undone coral this is also pretty confusing

If I add a force to my object (2,0), its velocity will keep growing. I would like the maximum velocity generated by this force to be (5,0) for example. However, I can't just clamp my velocity because if I have another object that affects the velocity of my object, it will conflict with the first force

merry hill
# merry hill I'm making instances of classes using constructors and calling them with the pro...

for example if i have the method

public T Method<T>() where T : Foo
{
    return Activator.CreateInstance(typeof(T), someString);
}```
then Method<Foo>() works fine but Method<Bar>() throws an error as there is no constructor with a string parameter
and i would like to know if its possible to still get that empty constructor even when i pass the string (as the alternative would be making a Method override for each child class with the correct parameters or creating a constructor with a string and I have quite a few child classes)
undone coral
#

it's too abstract

#

what are you trying to do

merry hill
#

i would like to make a copy of a class instance that keeps the constructor parameters that i used on the original

undone coral
#

@merry hill i'm worried the answer isn't succinct lol

#

don't tell me what you're engineering or how

#

just tell me what htis is all for

#

i believe in you

#

you can tell me succinctly

merry hill
#

not my first language, trying to find the words, gimme a minute :P

undone coral
#

okay lol

#

that's okay

merry hill
#

yeah now that i think about it theres probably a better way
because i have a bunch of static instances of those classes as presets that id like to create non static copies from to use
for example i have a preset for a certain type of wall you can place and id like to create a wall in the scene from that preset
(bad example, theyre not just GameObjects to Instantiate, rather class instances)

thin wagon
#

And I’ve heard that transform access arrays are expensive

undone coral
undone coral
#

why do you need something so generic?

#

even if you had 100 classes you needed to copy, authoring 100 Copy methods will take around 1 hour

#

which is nothing

#

you probably have only 5 classes you need to copy

#

ever

#

you might be able to reduce it to like 1

#

but you have to tell me what you are trying to do

thin wagon
undone coral
#

if the thing you need to copy is mostly primitives, struct copies "for free"

merry hill
undone coral
#

okay

trim shard
#

guys, how decode JWT by site jwt.io in unity?

undone coral
#

why do you need to decode a JWT in unity?

#

there are many libraries that do this

trim shard
undone coral
#

well surely you've found a library

#

to do this

#

it's in google

#

what data are you expecting to decode from this token?

trim shard
plush elk
#

hey guys I am trying to implament a state machine for an NPC, that npc can hear sounds, and if he hear a sound its priorities change to that action, is it good idea to make a parent substate "listening" and having other children substate like "iddle" and "patrolling"?

#

oh and another thing, right now I have the code to search for a new waypoint to explore into the idle state, should I create a separated state to define the next point to explore?

trim shard
#

KeyNotFoundException: The given key 'alg' was not present in the dictionary.

humble onyx
# trim shard

might be worth to attach the debugger and halt there to see what is in the headerData Dictionary

trim shard
scenic forge
scenic forge
trim shard
#

I did not try 🌚
first time using, i will try

jolly token
#

In Unity Test runner with performance benchmark extension, how can I make a build for testing that is not a Development build? What is point of benchmark extension if they don't allow that by default? 😕

#

I tried building and running from command line, but seems like it still generates development build

jolly token
#

This looks like just building regular game executable not for test runner

#

What is RunTests?

modest needle
jolly token
#

Don't tell me it's ChatGPT-generated

bronze geyser
#

When does an assetId ever change (if ever)?

modest needle
modest needle
long ivy
finite pond
#

The user can manually zoom the camera.

#

This change of orthographic size triggers a full canvas rebuild.

lucid gust
#

What Unity Gaming Service do I need to use if I want to put non player specific data on the server for all players to fetch from (e.g., Character Base Stats).

hybrid trout
#

I have had this issue I just reverted my editor

undone coral
#

what's the idea?

finite pond
#

not really sure what you're getting at

#

it lags in the editor

#

it doesnt in the build, but i still care about it

#

im using overlay canvases now

#

it fixed the lag 100%

undone coral
#

okay

#

so it sounds like you figured everything out

finite pond
#

yep

undone coral
#

you said some unspecific stuff about something

finite pond
#

didnt expect camera space canvases to perform so poorly

undone coral
#

then it sounds like you chose the fix that already worked for you

#

i don't think that's the issue

finite pond
finite pond
#

the documentation itself states the the canvas rebuilds on camera change

undone coral
finite pond
#

all other channels dont make sense either lol

undone coral
finite pond
#

lmao

#

whats the point of an idiot like you trying to help if you just end up trying to unsuccessfully roast people

#

i dont think this server is for you

undone coral
undone coral
# trim shard

i cannot tell if you are using a testing endpoint, but you posted a JWT, which are all bearer, for something that interacts with a crypto wallet, and also this token expires Jan 03 2023

#

so i think you are in some jeopardy

#

you probably want to work with this API on a separate server

undone coral
#

so if you posted a username and password to something, and got back a JWT, it's already sort of screwed

#

for example, when you tap login with facebook, login with google, login with tiktok or whatever - do you observe ever putting in your username and password in the app that offers those login options? no, you are navigated to a website

keen cloud
#

is it possible to have a button as an arg to a method and use it to later end a task that that method creates? I tried to do it but i probably have incorrect syntax

#

it works when the process is public static but not otherwise

#

I begin the process later in the code

#

this just comes up with process not found

cerulean spade
#

Is there any way to get around the fact that any gameobject in the scene can call public methods on your scripts?

#

For an example, I have a game object that interacts with the UI, but instead of the UI, any game object in the scene can modify its parameters instead

timber flame
#

How can I avoid casting like below?

 public interface IProfession
    {
        void Do(Task task);
        void Cancel();
    }
public class Builder : MonoBehaviour, IProfession
    {
        private void Start()
        {
            GetComponent<ProfessionCollection>().Add(TaskType.Build, this);
        }

        public void Do(Task task)
        {
            // run logic
            var taskData = task as BuildTask;
            //taskData.Data.Path
        }

        public void Cancel()
        {
        }
    }

There are different tasks and professions
Task (BuildTask, CarryTask, etc.) --> Data Profession (Builder,Carrier,etc.) ---> Logic
Data (Task) are inside queue (priority queue). After dequeue, A specific job should start with that data

Queue: Task1,Task2,...,etc.
Dequeue: Task1 (Task)
BuildTask (Data)--> Builder
CarryTask (Data) --> Carrier

thin wagon
#
ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.```

I could use some help understanding the last sentence of this error log, how can I solve this? I understand that it only wants me to access indexes of the array that are of the same index as the job index but I dont know what a double buffering strategy is?
austere jewel
#

If you're aware of what you're doing and you know you're only reading and writing from an index once, like if you've just offset the index by a fixed value, then you can also just mark the collection with [NativeDisableParallelForRestriction]

thin wagon
#

This makes sense in concept but I guess I'm a little confused still

        allignSteeringForce = rb[index];
        for(int i = iTotals[index]; i < fTotals[index]; i++){
            allignSteeringForce += (Vector2)velocities[i].normalized;
        }```
In this example I'm just adding forces from multiple indexes into one variable then adding that variable to an empty Vec2 list would ```[NativeDisableParallelForRestriction]``` be valid in this context?
#

iTotals is the start point and fTotals is the finishing point essentially

austere jewel
#

Are you only reading from velocities?

thin wagon
#

Yes only read

austere jewel
#

If you're only reading from collections you should mark them as [ReadOnly]

thin wagon
#

Gotcha will that fix my issue? or is that just a general good idea/practice?

austere jewel
#

If they're read-only then you can access any index because there can't be a write conflict

austere jewel
# thin wagon Ahh gotcha thanks so much 😎

Note that you should also use [WriteOnly] where you can. Not only does it help with this sort of thing, but it also fixes warnings that can happen when you've scheduled jobs together that read or write to the same collection. I would like it if they were inferred when the code was compiled, but for now it's good to get into the habit of using them wherever you can.

thin wagon
#

Yeah I saw the readonly and write only but had no clue what they did outside of restricting what I could do with the array. Makes sense now 😎

undone coral
undone coral
austere jewel
#

I doubt there'll be a logic difference there. The issue is probably more to do with how the process is being started, not the button

modest needle
thin wagon
#

How could I go about returning values from a job? I have a job that calculates a Vector3 velocity to apply to a rigidbody but you cant apply it inside the context of the job so how can I re-assign the value of velocity[index] so that I can read the changed result in a job manager

#

or even is there a way that I can have rigidbody's in the job? (I couldn't find any real helpful resources on this)

cerulean spade
# undone coral what do you mean? what are you trying to do

OK, so Im making a game that's similar to Besiege, you build machines out of parts, and I have a gameobject called builder which renders the UI for building, as well as has scripts on it relating to using the parts, moving them around. I want these scripts to communicate with each other, but this creates the problem of exposing methods to all other scripts in the scene, so now, theoretically, any gameobject could add a new part to the machine, and it is not supposed to have that level of access

trim shard
#

Guys, I have this error in the polaris asset, but it only happens when I create my scripts, as if it were conflicting with my scripts

undone coral
#

you own 100% of your source code

#

so you can always go and change the access modifiers anyway

#

they are as much of an agreement with yourself as "i will not use the wrong methods"

#

do you see what i mean?

cerulean spade
#

Idk i just don't like it

#

I can't change access modifiers because I need the scripts on the builder object to communicate with each other

#

So yeah I can make an agreement with myself

#

But it just seems wrong

undone coral
#

hmm

#

what i am sayin gis, the access modifiers are also an agreement with yourself

#

i appreciate you are trying to do this stylistically in a consistent way though

cerulean spade
#

And why am I attaching code related to UI and other non 3D things to an object in 3D space

#

Just seems unintuitive

undone coral
#

i don't know what that really concretely means. it seems reasonable to me that you have a TooltipOnHover script attached to a 3d object, whose job is to show 2d ui elements

#

for besiege, some stuff is tightly coupled, other stuff is decoupled. it's impossible to do 100% one way or the other

#

and stay sane

cerulean spade
#

Well, there's a script for the UI toolkit rendering

#

And responding to button clicks etc

#

That's the UI part

#

That communicates with other scripts like, the tools, move, rotate, etc

#

All this is on one "builder" object

#

Which is a gameobject that doesn't render

#

Just holds scripts

#

I say it's a 3D object because it's in 3D space shared by the other game objects, has a transform

opal nacelle
#

I have a scriptable object which contains data which is many classes deep. Prior to calling AssetDatabase.CreateAsset(scriptableObject, path), every field of the scriptable object is set correctly. But, afterwards, one certain type of field becomes null afterward. I have tried adding [SerializeField] to the field in question, but that does nothing.
The field in question is not a unity object.
The field is a custom class which extends Collection.
The field definition is like the follow:

[Serializable]
CustomClass : Collection<WrapperClass<ClassToWrap>>

and WrapperClass and ClassToWrap are marked as [Serializable] as well.
In addition, the field does in fact show up in the unity inspector. It just does not get serialized correctly it seems.
Any idea on how to fix this?

jolly token
opal nacelle
jolly token
#

No

#

Use them as field

opal nacelle
#

Is it possible to fix the issue without doing that? That would require a relatively large refactor.

jolly token
opal nacelle
opal nacelle
jolly token
opal nacelle
undone coral
#

how much data is in this object? like how many lines of yaml is the .asset file that corresponds to this scriptable object file

fickle zodiac
#

We constantly have issues with Scriptable Objects. Changes to Scriptable Objects don’t show up in github commit changes.

#

has anyone experienced this?

#

any advice on how to mitigate these issues?

austere jewel
#

Make sure you have hit Save Project, not just CTRL-S

#

I personally always rebind it to ctrl-shift-s

opal nacelle
timber flame
#

Task type is base (parent) class. I want to map task data to the corresponding logic type.
Queue: Task1,Task2,...,etc. (Task type) Dequeue: Task1 (Task) BuildTask (Data)--> Builder(mono) CarryTask (Data) --> Carrier (mono)

jolly token
timber flame
#

I said, Task types are just data

#

After dequeue, a system decides which worker (builder, carrier,etc.) should handle it

jolly token
#

You’re already using inheritance and have coupled type and worker

#

It’s not like you cannot, more like you don’t want to.
Sure, if you don’t want to use virtual method then only option is utilizing type information, which is casting.

timber flame
#
public class BuildTask:Task{
   public BuildTaskData Data;
   public Builder builder;
   public override void Do(){
     //...
   }
}

Instead of

public class Task{
   public int Id;
   public int Priority;
   //..
}
public class Task<T>:Task{
   public T Data;
}
public class BuildTask:Task<BuildTaskData>{
  
}

public class Builder:MonoBehaviour{}
jolly token
#

You can pass the parameter where Task can find builder

#

Or carrier, task can decide what to find

stuck onyx
#

lets say you have to save up layers the best way you can.... Im thinking to group certain layers in 1 but i need at certain point to be able to discern between the raycasted elements to take different actions... I thought about using the different components the gameobjects have but the GetComponent is expensive... so i thought maybe to use the gameobject name

#

for example i had layers Animals, People

#

Im thinking to merge into "Npc"

#

and all animals would be instatiated with a name "ani_xxxx"

#

so when i raycast npc i would know by the name those who start by "ani" are animals

#

Is this sollution bad? do you have any other better?

stuck onyx
#

or tryget is not as expensive as GetComponent?

compact ingot
stuck onyx
#

slow

compact ingot
#

TryGet is about 10 times slower than a direct (cached) reference

#

it takes on the order of 20 - 80 nanoseconds

stuck onyx
#

yeah i know, thats why im asking if there's any alternative to discern gameobjects in the same layer (Besides using components)

#

like using the tag

#

but im scarce on tags too

compact ingot
#

TryGetComponent is the best way in terms of modularity, robustness, separation of concerns and overall maintainabiliy

stuck onyx
#

uhmm. OKay you convinced me

#

😄

#

thanks a lot @compact ingot , whats the bad part on doing the name approach i suggested? several guys told me thats a bad idea but no one told me why

compact ingot
#

Tags are just Layers without the limit of having just 32 of them and also without any performance optimization

stuck onyx
#

i had understood comparing tags was extremely fast

compact ingot
compact ingot
#

TryGetComponent is extremely fast when compared to FindObjectOfType<Foo>().First();

real blaze
stuck onyx
#

but now i see i can use as many tags as i want.....

#

hmmmmm

compact ingot
stuck onyx
#

yeah i guess youre right anikki

real blaze
compact ingot
stuck onyx
#

linq has been extremely improved in last versions

#

still, i dont use it too much

compact ingot
#

and Linq is by no means slow, this is a complete myth perpetuated by people who don't understand what it is

real blaze
compact ingot
#

an IEnumerable has no concept of an index

real blaze
#

my bad. I meant first returning value

compact ingot
#

an IEnumerable does not even guarantee that any item is in memory yet. It is a (potentially) lazy collection, which gets evaluated only when the item is accessed, i.e. by .First()

real blaze
#

(do a reset() before, if the list is already iterated through)

compact ingot
#

idk what you mean

real blaze
compact ingot
#

sure, but why? linq does the exact same thing (but optimized depending on the actual most derived type of the IEnumerable)

real blaze
#

that's exactly my question too, wise versa tho. that why would we use First() if the alternative does the same thing in 1 line too 😅

compact ingot
#

btw, you can do

 Enum.GetValues<VerboseFlags>()[0]
real blaze
#

well that's an array, yeah

#

anyways. if it's alright, I'll repost my earlier question :p

#

‌‌ ‌
Question: imagine red circle is cornered & is still, and green circle collides with it. during this OnCollisionEnter2D, when I apply the blue force to the red circle, what happens is that the red circle stays still, and the green circle receives the blue force and gets bounced back.
does anyone have an idea how to make the red circle have that blue velocity?

  • I tried applying the blue to velicty
  • tried applying it to AddForce with both Force and Impulse params
compact ingot
#

Also consider that Linq is implemented in a way that you can provision its queries with optimizations for a given (custom) data structure and make these optimizations transparent in code that only is concerned with expressing the query (and not optimizing it every time)

compact ingot
real blaze
#

even if I set the blue velocity to a crazy high value, the red stays put...

real blaze
# compact ingot Also consider that Linq is implemented in a way that you can provision its queri...

I can't fully understand what you mean. my EN isn't perfect so it could be that.
if you mean to consider that LINQs are usually there for easier data structure rather than super performant methods, well yeah, that's their sole purpose. I use them a lot. My issue was only with the First() extension that seemed redundant to me. as we can already get the first index of any index based list by [0] and as for IEnumerables, well, it's bad structure to want the first index out of an IEnumerable anyway

#

also, if it helps, this is the source code for First() extenison (formatted to reduce text size)

public static TSource First<TSource>(this IEnumerable<TSource> source) {
  if (source == null) throw Error.ArgumentNull(nameof (source));
  if (source is IList<TSource> sourceList) {
    if (sourceList.Count > 0) return sourceList[0];
  } else {
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
      if (enumerator.MoveNext()) return enumerator.Current;
    }
  throw Error.NoElements();
}```
compact ingot
oblique obsidian
# real blaze ‌‌ ‌ Question: imagine red circle is cornered & is still, and green circle colli...

If the black walls are static, the red ball is at rest and the green ball is hitting the red one, neglecting the direction of the velocity vector, what happens is that the energy from the green ball is passed over to the red one, then the red one passed it over to the black walls, that pass it back to the red ball, that passes it back to the green ball. Result, the green ball files back to where it came from and everything else stays still. The blue vector gets added up to the resulting one. It's physically correct as per I understand it.

real blaze
compact ingot
# real blaze I can't fully understand what you mean. my EN isn't perfect so it could be that....

LINQ is designed to be a unified API for all types of data queries and its particular power lies in its ability to consume custom implementations of how the underlying data structure is accessed (be that a database, list or anything else), this also means that it can be particularly fast without the user of the API neccesarily having to care about how to make it fast. Ofc this has limits, but it would be false to say Linq is "slow" because it can be used in sub-optimal ways. There is no redundancy in having [0] and .First(), they are completely different conceptually and semantically, even if in a special case they yield the same result.

oblique obsidian
#

Keep in mind that we are talking about rigid bodies

real blaze
#

yes

oblique obsidian
#

The trick to have the red circle moving would be to add the blue vector to its velocity right after the "second" collision with the green one, not sure how to implement it though, I'm not at the PC right now

real blaze
oblique obsidian
#

Try to log every collision from the red circle point of view, I am not sure how unity handles this, from a logical point of view you might have up to 4. You want to apply your blue vector after the last one btw

#

Your trigger might be when green circle starts moving backwards

real blaze
# compact ingot LINQ is designed to be a unified API for all types of data queries and its parti...

but it would be false to say Linq is "slow"
well, LINQ is objectively slower than doing something manually the right way 🤷‍♂️ isn't that right?

There is no redundancy in having [0] and .First()
look at it this way. if you have a class that has index operators, you use [0] and not First(). if the class doesn't give you an index operator or any native way of getting it's first element, then it's clearly not supposed to be accessed in that way

real blaze
#

@oblique obsidian seems it all happened in one iteration

real blaze
#

the velocity gets zeroed out even if the blue force is a really big value

real blaze
undone coral
#

i only use layers for collision rules and camera rules. using them too much for logic is painful

real blaze
#

@oblique obsidian solved it by increasing the red circle's mass to be greater than green circle

jolly token
#

First() is shorthand for all that

oblique obsidian
#

Sorry I was outside for groceries and stuff and I missed the messages

buoyant leaf
#

I am having trouble with giving objects velocity when parented

#

I am making this vr game that involves throwing an axe

#

by using the controllers local velocity

#

so before I give it its throwing direction I unparent it, for it to be thrown outside of the controller

#

but for some reason, it decides that it should be thrown in the direction of the original player's direction then the direction I'm giving it

harsh flicker
#

Good afternoon, my name is Adrian and I am making an augmented reality application to present it in a national competition but when compiling I have this error if any of you can help me I am eternally grateful and thanks in advance

opal nacelle
#

does unity support serialization for classes that implements IList?

opal nacelle
# sage radish No

ok. does it support anything like that, or am i best off creating a wrapper class for a list?

sage radish
opal nacelle
#

ya that might be easiest to do (re: SerializationCallbackReciever). Then I don't have to rewrite the whole class

harsh flicker
# harsh flicker Good afternoon, my name is Adrian and I am making an augmented reality applicati...

CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Hub\Editor\2020.3.41f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Users\adria\Downloads\gradle-6.9.2\lib\gradle-launcher-6.9.2.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"

Environment Variables:
RegionCode = LA
USERDOMAIN = GAIBOR
ProgramFiles = C:\Program Files
TMP = C:\Users\adria\AppData\Local\Temp
PROCESSOR_ARCHITECTURE = AMD64
PROCESSOR_REVISION = 7e05
OneDriveConsumer = C:\Users\adria\OneDrive

regal glade
#

What's the method to raycast on screen pixels, when I want to ray cast on many screen pixels at once? Is it just like looping through Ray ray = camera.ScreenPointToRay(new Vector3(0 to screenWidth, 0 to screenHeight, 0)); ???

#

or is .ViewportPointToRay better if you want to take FoV into account?

undone coral
#

that's what it is probably telling you at least

#

otherwise you have to find the real logs

#

you should also be using a different version of the editor ify ou're targeting the quest

formal egret
#

Does anybody here know how I can get pixelsize using ortographic size and rendertexture sizes? This is what I'm trying to do:

        float yOffset = campos.y / pixelSize;
        Vector2 offset = new Vector2(xOffset, yOffset);
        Vector3 snappedCamPos = new Vector3(Mathf.Round(xOffset) * pixelSize, Mathf.Round(yOffset)* pixelSize, campos.z);```
I can't for the love of god figure out how to get the size of a pixel
#

I somehow need to piece ortho size together with aspect ratio and rendertexture sizes to get a pixel size variable

#

and it breaks my brain

jolly token
formal egret
#

Possibly?

formal egret
thin mesa
#

not an advanced question

frozen imp
#

@digital knoll Don't cross-post. And instead of spamming the question everywhere rephrase it so it can be understood clearly what you want to do. In #💻┃code-beginner

keen cloud
#

How come this freezes the UI when pressed and how would I format this to not?

#

How do you return a value from an async function and not freeze the UI

sly grove
#

don't await it

keen cloud
#

im doing that to test it

#

the thread.sleep

#

how would you make it run in the background regardless

#

or does thread.sleep affect not the current context

#

like does that affect the actual main thread

sly grove
keen cloud
#

even if i dont use await it still freezes

#

i felt like i already tested that

#

lol

#

should the RunDiagnostics not be async?

#

nvm i put await in the method and it worked

#

thanks

#

very cool

west scarab
#

Any ideas why I'm getting a 64 length array when I'm getting the pixel data of a 256x1 texture?

somber swift
west scarab
#

Maybe the method doesn't support it, it has no type checking on the generics 🤷‍♀️

somber swift
jolly token
#

I think it the type supposed to match with your texture format?

#

GetPixelData does not allocate memory; the returned NativeArray directly points to the Texture system memory data buffer.

#

So it's not going to convert type for you

west scarab
#

The texture type is RGB9e5Float, what kind of value type do I use for that? 😅

#

Maybe I'm better off with a Color32[] and SetPixels32...

jolly token
keen cloud
#

how would I pass a returned value into another method without crashing my game lol

#

anytime i use .Result my game crashes

#

is there a specific way to do this?

sly grove
#

when it's completed, then you can read the result.

keen cloud
#

So use a co routine?

sly grove
#

sure

#

or Update

keen cloud
#

What would the syntax of that even be

#

Like how would you tell it to wait without await

sly grove
#
IEnumerator MyCoroutine() {
  yield return new WaitUntil(() => myTask.IsCompleted());
  Debug.Log($"Result is {myTask.Result.ToString())!");
}```
#

Use UniTask if you want to do this elegantly with the async/await stuff rather than a coroutine

keen cloud
#

Okay thank you I’ll test that

keen cloud
#

is unitask not installed?

#

like is it external

undone ferry
#

is it possible that altering a variable/reference which is being used by a coroutine can cause the coroutine to stop? (undesirably)

keen cloud
#

hm it is

#

not to you speaking to my previous

#

apologies

undone ferry
#

nw

#

im using a coroutine to animate a UI element, and I'm trying to make it input-spam proof. But if i spam it (edit the target value that the coroutine animates towards) from the editor, then it occasionally breaks.

#

the coroutine appears to just stop without running its final code

#

ok i think i narrowed down the cause to the editor itself

#

doing this with actual inputs rather than spamming the inspector at runtime seems 100% stable

keen cloud
modest drum
#

How do I Texture.PackTextures() normal maps? Right now it's showing these weird seams.

#

And I think it has to do with how unity formats the channels of a normal map, and Texture2D.PackTextures doesn't automatically support that.

hallow elk
#

Hey all, I made a stupid mistake and need a quick bandage until I can fix the larger issue. I have several scripts, Foo and Bar that derive from a base class we'll call BaseFooBar. Foo has a field called SomeBool and Bar does not. Because I was not thinking ahead and made these classes long ago before I realized what I was really doing, I made a script that gets a component BaseFooBar and gets a value for SomeBool:

...
            if (GetComponent<BaseFooBar>().SomeBar)
            {
...

Now, I know that I need to go through and fix this issue properly but that's a larger issue because it's not quite as simple as a couple of classes. I absolutely do intend to fix it properly. However, I need a quick fix now. Is there a way to check if a component has a particular field before checking its value?

zenith ginkgo
#

I'm er.. No i don't think thats possible

#

Maybe with some weird reflection? but thats beyond me

#

if SomeBar physically doesn't exist, there can be no check to see if it exists

hallow elk
#

I know in base C# you can usually do a type check for the field. I'm not sure how that would apply (or if it even can apply) to a component

#

like if (type.GetField("MyBool") != null

hushed fable
#

Yea you can get a list of fields/properties with reflection. Alternatively you could differentiate the classes by throwing an interface on the types with that field present and checking against that

#

Components are types like anything else in C#, so any reflection material for getting fields would apply.

hallow elk
#

Would it be something like this:

Type type = GetComponent<BaseFooBar>().GetType();

        if (type.GetField("SomeBool") != null)
        {
            bool myBool = (bool)type.GetField("MyBool").GetValue(obj);
        }
#

I really just need to go through and fix this properly. Looking at this just hurts

thin mesa
#

If you just want to access the SomeBool field on from the Foo class derived from BaseFooBar, just cast to Foo

var baseFooBar = GetComponent<BaseFooBar>() ;
if(baseFooBar is Foo foo) 
{
    foo.SomeBool = true;
} 

Unless I'm misunderstanding the point of this 🤔

brisk pasture
#

feel there is never a case where i would want to get a field by name like that with reflection

#

where just casting to the concrete type of a interface that has what you wants would not be better

sly grove
brisk pasture
#

also would never try reflection logic like that for runtime in a game

jolly token
#

Unity:

hallow elk
sly grove
#

This seems like something that would be solved pretty simply with interfaces or abstract classes.

hallow elk
# sly grove If it doesn't have the variable why are you trying to access it

I have several scripts, Foo and Bar that derive from a base class we'll call BaseFooBar. Foo has a field called SomeBool and Bar does not. Because I was not thinking ahead and made these classes long ago before I realized what I was really doing, I made a script that gets a component BaseFooBar and gets a value for SomeBool

hallow elk
sly grove
#

Just use is to downcast

#

Why are you doing reflection

hallow elk
#

Right now, the script is like this:

...
if (GetComponent<BaseFooBar>().SomeBool) {
...
#

and again, this is a simplification of a much larger and complex setup.

sly grove
#

This is some #💻┃code-beginner stuff to be perfectly honest.

if (myObject is Foo f){
  bool b = f.SomeBool;
} ```
brisk pasture
#

also really would try and rethink you structure instead of hacking something ontop like this

hallow elk
#

I'm going to quote this for the third time:

I absolutely do intend to fix it properly. However, I need a quick fix now.

#

Like, seriously, I know I did it wrong, and I am going to fix it. I am asking for help for the moment so I can solve a more pressing issue

#

Imagine the fact that I am admitting I did it incorrectly and that I am going to fix it, and still people feel the need to condescend

brisk pasture
#

people are not trying to condescend, they simply know the path you were going down turns into a much larger headache later on

hallow elk
brisk pasture
#

but yeah if doing this, would leave reflection alone and do the is example like @sly grove suggested

hallow elk
#

Alright, I have tried using is however it's not quite going to work that way due to the way access is set up in this case. Which is to say that, currently, the script cannot access Foo, it can only access Bar.

brisk pasture
#

so issue is using reflection is fragile, slow and will make it harder to refactor later

#

its really mostly useful for tools that do stuff with code, or for editor tools

hallow elk
#

Right, totally. I'm essentially at the "I just need to get it to compile and fix XYZ", at which point I can fix the issue properly.

orchid marsh
brisk pasture
#

or via is like suggested so you can check that it can be cast and cast at the same time

hallow elk
#

is isn't currently working. I can try as to see if that at least gets it to compile, since I don't care about if it works at this point

brisk pasture
#

var b = a as Foo;

#

then you null check b to see if it worked

hallow elk
#

Right, but the script performing this operation cannot access Foo.

brisk pasture
#

why not

orchid marsh
#

What do you mean by cannot access Foo? It doesn't know of the type and it's existence?

brisk pasture
#

if its a type in your scripts folder it can access it

#

since its all in the same assembly

hallow elk
#

Exactly. There are some conflicts in the access due to a miscommunication, which is a larger issue

brisk pasture
#

if its in a other assembly its up to you to make sure its referenced correctly

#

either way if the type is not there, reflection will fail as well

#

since it also needs that type information

orchid marsh
#

If you don't know what you're working with, you are in an unknown territory and headache valley. There is no salvation. Reflection, safe coding practice, and good luck.

hallow elk
#

No worries. I've been working on the better, more complicated, but more correct solution for a while now.

brisk pasture
#

generally better solutions are not more complicated

hallow elk
#

It's just old mistakes from code I wrote a couple years ago that was done wrong, biting me in the butt

brisk pasture
#

if you are going down the path of trying to access thigns on types you do not have, and using reflection. you literally would be better off deleting it and starting anew

hallow elk
brisk pasture
#

also you never explained why you do not have access to the type

#

i been programming most of my life at this point in many languages, complexity is future tech debt

hallow elk
#

OK, so I mentioned this is a simplification, but basically it's not actually Foo and Bar. It's two different versions of Foo from two different things that were combined improperly. So there is a version of Foo that has SomeBool and a version that doesn't, and both derive from the base class in different namespaces, and the other script takes in the base class instead of the derivative

brisk pasture
#

so you have access to both then

#

if its only namespaces seperating them

austere jewel
#

and for some reason one is in a different assembly that you cannot change?

hallow elk
#

Yes.

brisk pasture
#

you jsut need to provide a alias or full name

hallow elk
#

Right, I just have to do that on a lot of different scripts that are stuck referencing the wrong Foo. Once that's done, then I can just remove the wrong one, fix the references, and it'll be fine.

#

It's a longer, but more correct solution to fix it. I don't mind

brisk pasture
#

ok, but are they only in different namespaces

#

or do they exist in different asmdefs or different dlls?

hallow elk
#

Unfortunately, the issue is because of namespace capitalization

brisk pasture
#

ok, but why cant a fully qualiifed name be used then

#

if its only about namespaces its easy to work around

#

or a alias in your using statements

sly grove
#

There's not really a difference between Foo and Bar and A.Foo and B.Foo

#

Classes with the same name in different namespaces are just... Completely separate classes

hallow elk
#

You might know how Unity has issues when there is a capitalization difference between a script name and script filename. This causes some issues when git is involved, because git generally doesn't read changes in capitalization as changes

brisk pasture
#

sorting out that is a way more solveable problem then what you are trying to do

sly grove
#

Git has no problem with it. The problem would come only from case insensitive filesystems

brisk pasture
#

also its not git, its windows that has the issue

sly grove
#

Such as Fat32

hallow elk
#

Regardless of who has the issue, it leaves a problem when there are conflicts that don't appear to be conflicts.

sly grove
#

It'd be quite rare in this day and age to be using a FAT32 partition

brisk pasture
#

if you fix it on something that is case senstitive and clone it back cases will be all correct

hallow elk
#

So, as mentioned, the longer and more correct solution is to go through and fix all the references manually and reserialize everything. This would be much easier if I could get the code to compile, because at that point it should all serialize and I can just remove the conflicting script

brisk pasture
#

as long as the meta file name changes with the file name, references will stay intact

hallow elk
#

I'm not bothered by having to do it the long way. I was only hoping to skip a step. No worries.

zenith ginkgo
#

if you're going to fix it later, fix it now

urban warren
modest drum
#

How do I properly use Texture2D.PackTextures() on normal maps?

nova summit
#

** Does anyone here use UnityEvent's extensively? I see it a nice way to de-couple the code but as the progress goes it will be a nightmare to track which is changing what and from where. Any insights on it?**

compact ingot
#

If you want to have editor assigned messaging with actual decoupling/IoC and you are okay with the mess that can produce, you’d go with mediator SOs (the Ryan Hipple thing)

light vine
hexed meteor
#

Does anyone have a moment to help me figure out why my playerprefs manager script does not seem to save/load player prefs?

#

Having used player prefs without any trouble in the past, I cannot figure out why this one doesn't work

#

(I'm doing all of my testing in build and the methods are all being called successfully as confirmed by debug.logerror prints)

hexed meteor
#

Why this won't work 😭

severe topaz
#

@hallow elk you were looking for TryGetComponent, and "is" for pattern matching

nova summit
nova summit
# compact ingot If you want to have editor assigned messaging with actual decoupling/IoC and you...

I see using SO's as a mediator more like the workaround for having shared memory problem. Please correct me if i'm wrong.
Why I see more like a workaround but not a proper solution is

  1. I need to have SO classes like for ever parameter combination (Float variable, Int, float +int and so on) which I see will work for smaller set
  2. If I go and create SO class for each event, creating an instance of SO from the class sounds more like a patch as i see only one instance object is required for that specific event. Which doesn't sound great.
    By SO instance I mean the asset created from SO class.
#

But one nice thing is it shares the data nicely making whole thing decoupled If i compromise on some coding style.
@compact ingot

light vine
tulip cliff
nova summit
tulip cliff
light vine
regal olive
#

Best way to get which side a cube has been hit?

#

if this was the wrong channel, please tell me btw haha

compact ingot
# nova summit I see using SO's as a mediator more like the workaround for having shared memory...

(1) yes, that is the entire point of it, maximising modularity and pushing semantics into the design space (this can be a good or a bad thing depending on your workflow/team needs & goals)
(2) idk what you mean, you'd create a new instance for all semantically different events, messages or data channels you'd need, the type of the SO and the semantics of it can be entirely unrelated (they could all be the same type). You are also free to use any struct as a value type for your SOs to facilitate complex messages (i.e. a Vector3 is a set of three floats, or an event may want to pass along source reference and some arguments)

The seminal Unite Talk (video on yt) on the subject explains all the benefits very well, just note that all the benefits can also be problems, depending, again, on your needs & goals.

#

You can solve the same thing in code only by using a dependency injection container or doing IoC with manual DI.

#

In no way would Unity Events "for everything" be a better alternative.

nova summit
#

Best part with SO compared to code approach is SO being a physical asset, easy to manage. But code has its own benefits though.

Btw, do you mean creating a new SO class for every event type would be fine? That ways I see it more comfortable about the way its coded rather than having combinations of parameter type classes.

#

Also I wish unity creates something like a "data pipe" or message channel kind of things so that it won't more like a patch to how SO's are used in this context.

obsidian glade
#

far harder to manage in some respects

nova summit
#

Because it wont let us to touch the code and I see it more valuable

obsidian glade
#

ymmv, but in my experience no - the scriptable objects and binary unity objects in general are much harder to keep track of

compact ingot
#

it supports all common messaging patterns

compact ingot
#

you also should consider writing tools no matter how you solve your problem. Much of Unity's systems are very low level and do not automatically provide a great UX without custom tools.

#

SOs can be very easy to manage with some simple custom editor windows

#

the issue (and opportunity) with SO events is rather in the creative use they allow, so parts of your game logic will not be visible in code, actually most of it wont, and this can create problems, also if your team is not 110% disciplined about naming conventions and asset organization, it will be a mess

sage radish
#

What I don't like about using SOs for something like this is that you'll often end up with single instances of each SO type. That will quickly fill up the CreateAssetMenu, so you'd probably need to find some other way to create each instance.

compact ingot
sage radish
#

Still, it's a menu you'd literally use once just to create the single instance required.

compact ingot
#

you can create assets with a button in a window or inspector too

#

or a context menu action

#

there are plenty of things in unity menus that you only ever create once

#

never even used this one 😄

nova summit
# compact ingot its not a "patch" or "hack", get that out of your mind, a mediator SO is effecti...

So you mean, we need to ignore how the data pipe is created and only focus on its funtionality then. Is it me alone or do you agree that the SO's class can be very generic and the functionality it does is totally diff - this what makes me feel its odd.
For ex: Consider I create a SingleFloatParamEventSO and this will be used for diff types if events where single float parameter is required
VS
Creating a class which does point to concreate event name

Here the latter is more easy to debug where as first one tough to track down as the type is too generic in the code.

compact ingot
#

if you do it any other way you'd be better off using a code based Message Pipe

nova summit
compact ingot
#

you can create buttons like this rather easily

#

btw, i'm not trying to convince anyone, just hoping that you decide for/aginst SOs based on actual issues/opportunities

nova summit
compact ingot
#

i've had projects where i used SOs for UI data binding and config, ingame settings and maybe the odd global message but not for anything driving gameplay, so there is no requirement to be dogmatic about it

#

i'd probably advise against being dogmatic about any pattern in a game project

compact ingot
sage radish
#

I definitely prefer the code based approach and use it for my own event bus. Usage looks something like:

private void OnEnable()
{
    EventBus.SubscribeTo<PlayerDamageEvent>(OnPlayerDamageEvent);
}

private void OnDisable()
{
    EventBus.UnsubscribeFrom<PlayerDamageEvent>(OnPlayerDamageEvent);
}

private void OnPlayerDamageEvent(ref PlayerDamageEvent damageEvent)
{
    Debug.Log($"Player received {damageEvent.Amount} damage");
}

Where PlayerDamageEvent is defined as:

public struct PlayerDamageEvent : IEvent
{
    public float Amount;
}
#

MessagePipe looks similar but also screams enterprise/business

compact ingot
#

you can still expose these code-based event channels in the editor with some work on custom inspectors

golden cypress
compact ingot
sage radish
sage radish
golden cypress
#

I had only seen the eventbus pattern in Godot, where its more or less just a bunch of named signals (events)

sage radish
golden cypress
nova summit
#

So question is while EventBus is a very old concept which actually solves the problem in a better way, I wonder why SO's are being suggested for decoupling stuff*

#

Is it only because of less code - 🙄

sage radish
#

The editor and serialized fields are a very powerful tool and it would be silly to avoid it. But I do think you can go too far, like going all in on ScriptableObject Architecture, where everything from events to variables are defined as SOs.

compact ingot
#

there is nothing to add to his arguments and all the discussion is only about criticisms. what MentallyStable said is the conclusion you come to after trying it for a while yourself

#

you can't make an informed decision without ever trying all the options yourself, so whichever way you go, be confident its a valuable experience at least once. In any project you'll join (and don't write entirely yourself) you'll come across an unholy mix of every pattern ever invented and everyone will like you if you can just dive into it and start fixing bugs that eluded everyone else in their dogmatic worldview.

jade grotto
#

One thing the SO/linked-up-in-editor approach works quite well with is Addressables, new content and gameplay updates can be created in asset bundles without having to rebuild (and republish) the base game

nova summit
# compact ingot you can't make an informed decision without ever trying all the options yourself...

I tried both(event bus and SO's) the approaches earlier and also unity events.
I recently noticed SO approach is more discussed on internet and wanted to see what I thought about it is proper or not.
I see both the appoaches are totally fine as you mentioned if team is in sync about the approach used. MentallyStable's eventbus is what something I personally prefer as its more concrete at code level. However SO's shine as its more manageable from non-coders end which is a big plus in diversified team.

#

@compact ingot However, i'm convinced about your explanation too when you mentioned about semantics of an event will be defined at instance of SO. So I now have proper understanding on when to go with SO approach. Thanks for the details!

wintry dragon
#

https://answers.unity.com/questions/1934122/unity-ecs-10-generated-mesh-not-visible.html
I've been procedurally trying to generate voxel-chunk meshes in my game-scene in ECS 1.0.0-exp.12 (Unity 2022.2.0b16). In ECS 0.51, I was able to- but transitioning over caused the problem. As you can see, the mesh itself is being generated, but the render for it is not. Were there major rendering changes made to ECS 1.0? I would love some help on this and if any more information is needed, I'm happy to give it. Thank you.

buoyant nacelle
#

I want to make a modular spell system with a graph view. By modular, I mean that i can mix and match different types of behaviour and make as many unique spells as i want. How should i approach it? The way I imagine it is I have components with events. I just add components that happen on SpellStart and then these other components to events from these components. Not sure how to implement it though. I have Odin inspector.

compact ingot
rugged radish
#

Will there be any issues with meshes that have unused vertices ? I need to implement a lod stitching between segments and the solution I have in mind involves only regenerating the triangles and leaving the same vertex array. Which means that some of the vertices will be left unused. Are there're any non-obvious issues with that, like shaders acting up or something similar ?

sly grove
rugged radish
#

having fixed vertex indices sounds like a good trade off in this case

#

best thing would be to get access to the same API Unity's terrain uses to generate LOD-enabled heightmap mesh, but seems like you just can't

jolly token
rugged radish
jolly token
#

Yeah that'd be fine

fringe condor
#

After moving an object with position.lerp my object kinda locks in and I cant move it even when i try to move it from the editor, any idea whats causing it and how to repair it?

hoary prism
#

You're trying to move it but your update is overriding the position

modest drum
#

How do I properly use Texture2D.PackTextures() on normal maps? Right now the normal map appears reddish and seams are being shown when I try to use it on a model.

fringe condor
#

The last coroutine that moved the object has ended

fringe condor
#

no, not in update

hoary prism
# fringe condor

I'm kind of scared of asking what does StartCoroutine(Waiting(2f)); does....

fringe condor
#

I needed a fast way to wait 2 seconds, I know its a barbaric way of doing things

hoary prism
#

It's even more of a barbaric way than you think lol

#

Try

yield return new WaitForSeconds(2f)

hoary prism
fringe condor
#

No, I was just a complete moron and literally used that one line of code in a dedicated function

#

I suppose I cant have multiple yield return in the same function now can i

hoary prism
#

You can have a whole queue of stuff that happens one after another

#

After a delay

hoary prism
jolly token
fringe condor
#

Ok so I did that but it didnt do anything below my second yield return

#

no debug and didnt enter my function

hoary prism
#

Maybe the second coroutine didn't finish?

(Personally I've never used another coroutine inside a coroutine so no clue how that works)

undone coral
hoary prism
#

Also Jesus Christ that's a lot of coroutines inside a coroutine

undone coral
#

are you asking how to sequence things in coroutines, including other coroutines?

hoary prism
#

I see 3 just in that snippet

undone coral
#

did you author SmoothLerp?

#

you should be using DOTween

hoary prism
#

^

#

Probably one of those coroutines didn't exit

undone coral
#

you are showing screenshots of snippets of code. based on the only thing that is visible there, SmoothLerp is buggy, or you are disabling the game object this script is attached to during the coroutine you are yielding on before the log statement

#

@fringe condor does that make sense?

#

smoothlerp is probably something like while not the value is equal to the destination value

#

something bad

fringe condor
#

it checks for a minimum distance between my object and its destination so its not like it is dancing around it

#

The function aint buggy as it functions smootly in previous uses (from the same session of play mode)

keen cloud
#

How would you do async tests like this? I am getting that error

fringe condor
#

so i dont really have anything else besides something breaking with the yield

hoary prism
#

And like he said, try using DOTween, it's much simpler and easier way to do it

fringe condor
#

no, it check if the distance between is less than some minError

keen cloud
#

i can look it up if its something deep

jolly token
#

Coroutine is Unity specific feature

keen cloud
#

ah okay thank you

undone coral
#

you have to listen to what i am saying

#

and do it

#

if you want your thing to work

gritty quest
#

Can someone help me

#
  private void RaycastForEnemy()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.parent.position, transform.parent.forward, out hit, 1 << LayerMask.NameToLayer("Enemy")))
        {
            try
            {
                Debug.Log("Hit an Enemy!");
                Rigidbody rb = hit.transform.GetComponent<Rigidbody>();
                rb.constraints = RigidbodyConstraints.None;
                rb.AddForce(transform.parent.transform.forward * 500);
            }
            catch
            {

            }
        }
    }
#

I cant get the bullet to do anything to the enemy

gritty quest
#

?

austere jewel
gritty quest
#

my bad there was ppl talking in the other ones

austere jewel
#

That's not how discord works

gritty quest
#

ik I didnt wanna interrupt them

austere jewel
#

make a thread next time

gritty quest
#

alr

severe tundra
#

i asked this on the subreddit but decided to ask here too.
I have some code using the new netcode extensions, with network objects and all that.
Are there any good cheap server-options that will allow me to incorporate that code? The prices on the unity servers are a bit high and a bit confusing... It also seems like you cant choose a free package that will be cut off/limited, instead you need to pay if you go over (Which is scary seeing as i need to test it for performance and such)

#

i have no experience with servers... I tried converting some code to photon too but it seems a bit buggy and possibly not for my situation...

For an idea of what I mean: I am trying to re-code katamari, so there will be a lot of objects that do literally nothing until touched... then they do something... then do nothing again until the player that touched them leaves or is defeated. (I dont need tips on how to code it, just how to connect to a server or allow players to go player-to-player with it)

Looking it up i cannot tell if other server hosts will allow me to use this code or do I need to swap. If anyone has any experience with setting up a server (p2p or dedicated) it would be greatly appreciated.

flint geyser
#

I have a generic wrapper class. Can I make for it an implicit conversion operator to all of its inner value's base types (interfaces) which will return the inner value?

#

The class itself looks kinda like this

public class DecorationProperty<T> where T : class
    {
        public DecorationProperty()
        {
        }

        private readonly List<Func<T, T>> _decorators = new();
        private T _value;
        private bool _decorated = false;
        private T _finalValue;

        public void Decorate(Func<T, T> decorator)
        {
            _decorators.Add(decorator);
            _decorated = false;
        }

        public static implicit operator T(DecorationProperty<T> property)
        {
            if (property._value == null) throw new Exception("No value to DecorationProperty");

            if (!property._decorated)
            {
                property._finalValue = property._value;
                foreach (Func<T, T> funcDecorator in Enumerable.Reverse(property._decorators))
                {
                    property._finalValue = funcDecorator(property._finalValue);
                }

                property._decorated = true;
            }

            return property._finalValue;
        }

        public void Set(T value)
        {
            _value = value;
        }
    }```
warm trail
#

I'm doing networking in FLAX, very similar to Unity

I have a dictionary with object + name (set to connection ID to tie incoming messages to an object)

Then I have a list with name + location

Trouble is I cant for the life of me use the name from connection ID to read the index of the corresponding entry in the list

here's a snippet of code where i try to get the index but it gives me an out of range error.
Surely if I JUST put that name in then it cant be too big to use to read right???
I have asked many code wizards and they just don't know where I should go from here


List<_ClientsHolderDefine> _ClientsHolder = new List<_ClientsHolderDefine>();

//Create the object
var Clientsholderinput = new _ClientsHolderDefine(name, spawnlocation, 5, 2.5f);

//Add it to the list
_ClientsHolder.Add(Clientsholderinput);

//Get the index of the Clientsholderinput we just added
int index = _ClientsHolder.IndexOf(_Clientsholderinput, (eventData.Sender.ConnectionId));```
upbeat path
warm trail
undone coral
chilly talon
#

I'm writing a source generator for Unity, and I need to include a file as 'additional files'.

Has anyone tried this before, and if so. How did you do it?

This is what the compiler option /additionalfile:Assets/hello.json gives me.

A bunch of InvalidOperationException: Failed to add object of type XXXXX.

InvalidOperationException: Failed to add object of type `SubGraphAsset`. Check that the definition is in a file of the same name and that it compiles properly.
UnityEditor.ShaderGraph.ShaderSubGraphImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) (at Library/PackageCache/com.unity.shadergraph@14.0.4/Editor/Importers/ShaderSubGraphImporter.cs:116)
UnityEditor.AssetImporters.ScriptedImporter.GenerateAssetData (UnityEditor.AssetImporters.AssetImportContext ctx) (at <f7044ab663d344a2badf1160e57d1c1d>:0)
severe tundra
# undone coral do you have a screenshot of your game?

this is how it looks when played (Photon is disabled, I have a different github branch with photon-based code on it)

The items on the ball are childed to it and running no code.

When childed, items and the ball read a few things, meaning having a host is better for anticheat.

#

(ignore the text in the top left it hasnt been fixed yet)

undone coral
undone coral
#

what is this for?

chilly talon
# undone coral it seems like you've been at this for a while

Just picked it back up again.

I'm trying to read a configuration file, that configures the directories the source generator should use. Just having fun with Unity and SG, thought I'd generate an enum based on all sound files in a specific directory, that way designers can easily implement sound effects without having to manually type out the names and/or write code (or use scriptable objects).

#

I've done it before, but I had to use PATH environment variable to make it happen, I would love to be able to make it PATH free.

severe tundra
undone coral
#

and what's the idea with multiplayer?

#

let's say there was no lag

#

let's say your players had 4090s and a EPYC zen4 96 core CPU

#

would you make it look different?

#

and how do you control it right now?

severe tundra
#

multiplayer works already
i just need to figure out how to get it onto a server

using unity's netcode another player spawns in and both can pick up items
There are projectile weapons that knock items off other people.

You control it with WASD but that can be changed
You can only control your own player when both are spawned in.

my main issue is i cant figure out how to get a server or a p2p syncer that will work with unity's netcode stuff.

#

i currently test the multiplayer with the networkmanager (From a unitypackage) and it has a button to start a host/server/clent however it always seems to be on localhost.

undone coral
severe tundra
#

thats not what im stuck on...

undone coral
#

hmm

#

i know, but you're actually at the start, not the end, of this journey

#

and i make a technology that makes this all a lot easier. i'm just seeing if it makes sense for your game

#

like multiplayer katamarci damacy is interesting to me

severe tundra
#

and i dont really know for touch, i've done a bit with mobile but i do want this to be a PC game.
i have a lot of ideas for the games, there are powerups that have been coded but they currently only work singleplayer

undone coral
#

and grab the marble in front of you

#

okay

#

do you see how it's the same unity scene, different cameras, different inputs

#

it's local multiplayer, it's clearly networked

#

because you and i just donked marbles with each other

#

do you get it?

severe tundra
#

interesting,
ye i do.

undone coral
#

okay

#

i knew you would

#

it's local multiplayer but it's networked. that means your game is reality.

#

you can do this in urp too

severe tundra
#

two questions,
does this only work with mouse
would I need to re-write code that references other gameobjects?

undone coral
#

would I need to re-write code that references other gameobjects?
no. there is no netcode. it's like engineering a local multiplayer game, except you have multiple cameras

#

you connect your git repo, and it builds it and you have a link.

#

auto builds on push.

#

the plugin is extremely simple

#

you have to use input system. you would want your game to make sense for mobile, because then you have an audience

#

in the sense that you can share a link

#

and most people use their phones

#

as their computers

#

and they can Just Start Playing

#

just like you did with me

#

no faff

#

it's regular unity physics. no unity physics netcode synchronization warble garble. literally anything creative you can do single player, it works multiplayer

#

but of course all compatible with pc

#

i am just always on the look out for someone with an intriguing idea and skills

#

anyway think about it. i think you have a promising scene

#

you can add the plugin, it has only 1 script. then you add the git repo and you can mess with the link

#

you should be using input system anyway. that is the only compatibility issue typically for people to try

#

then you could e.g. use the obi physics packages

#

and do cool liquids, ropes and soft bodies stuff

#

and since the computers are extremely powerful, you can do whatever works well on your editing station

#

it will work well for the player

severe tundra
#

can you spawn in a new player object for each player...
because part of the issue is each player needs their own player object.
will it always sync every aspect of every object, or do i need to use some code to sync the objects player-to-player somehow

I dont really know where to get started with this.

undone coral
undone coral
undone coral
severe tundra
#

how does it sync, does it have a server it runs off of/is there ram etc?

undone coral
undone coral
#

the amount of computing resources you use are sort of negligible, so that's why the dashboard doesn't expose any of that. it doesn't really matter.

severe tundra
undone coral
#

i am glad you are intrigued

#

i think people who wanna do interesting multiplayer experiences in unity usually wanna use physics

#

and then you run into this hole where networking physics is ridiculously hard

#

this is the only approach that lets you be innovative with multiplayer physics, as a single person

#

if we had $10m-100m budgets like Blizzard does, we can make networked physics as good as the kind in like overwatch

#

the marbles are ordinary rigidbodies. there's nothing special. no scripts about networking in here

severe tundra
#

part of the issue right now is i need to remove some networking code i had in 😛

undone coral
#

yes, this is definitely easier when you are aware of it from the very beginning

#

however you might want to experiment with local multiplayer anyway.

severe tundra
#

ye ill think about it

part of my reluctance is that i do have the code ready for multiplayer
i just have no idea how to connect to a server with said code. (Other than using unity's servers which seem overpriced)

undone coral
#

for some inspiration for controls, you can look at my virtual test drive - http://appmana.com/watch/virtualtestdrive - this has tap, drag and swipe controls for driving

#

it's worth trying that link on your phone

#

so you can appreciate how nice it is to have hdrp in mobile

undone coral
#

you hard code your game to connect to it

#

and the server infers from the pattern of connections what to do

#

restart a game, wait for players, etc.

#

10 concurrents sounds like very little, but it's actually like 7,000-15,000 visitors from 9am-9pm, if a match is typically about 3 minutes

severe tundra
undone coral
#

yeah

#

on aws, you would use route53 to set up a domain that points to something that supports loadbalancing / proxying, like traefik nginx envoy haproxy or whatever, that's designed to route users to a web server

#

each player's client makes a REST request for a match. a matchmaker sends back the connection information to the clients

#

unity sort of has this already. you can also deploy it yourself, it's called openmatchmaking, it is ridiculously complex to deploy

#

then your clients use the information they receive from the matchmaker to connect to a real unity headless server instance, also running on a remote machine

#

i am addressing what you originalyl asked about, not how this system works

#

this system you just give it your source and it builds the game

#

it does all of this on the backend. i wrote my own matchmaker

severe tundra
#

ah
im confused because im not fully sure how either system works

undone coral
#

i evaluated openmatchmaking which is why i know so much about it

#

i think what's so confusing is that for multiplayer games, traditionally

#

you either have 0 players or 1,000,000 players

#

so nothing is engineered for in between

#

self hosted games work for in between, but those are sort of dead as an end user concept

#

too hard for people to do

#

self hosted meaning the end user's machine, if it's not an xbox, hosts the match.

#

steam also supports this. but understanding how steam networking does it all is another degree in multiplayernetworkology

#

what unity does is similar to what my system does. it starts -batchmode unity processes inside virtual machines on their/AWS servers, those servers connect to a matchmaker, your client connects to the matchmaker, the matchmaker assigns servers to clients, the clients receive that connection information and connect to those -batchmode unity processes

#

it is more complex

#

not necessarily in a good way. really depends on the game

severe tundra
#

tbh the main thing i wanted to be able to do is just have a main menu screen where you can type in a code
and if there is no lobby for that code, it makes one with you as host of the lobby
if there is a lobby with that code it would set you up as a client to that lobby

im sad there are no good videos on how to connect your code with one system to something.
The only one ive found that can connect to it is unity's own servers that are usage-based rather than package based so you cant force a cutoff.

undone coral
#

it's really complex software

#

the compute costs are nothing, that's true. it's literally pennies a year for unity to deal with your game

#

but you're paying for the software that makes this all actually work

#

in the case of a streamed game, the compute costs are much higher

#

lobby codes are still interacting with a matchmaker

#

but like i said you can use openmatchmaking

#

which is tremendously hard to deploy. i mean it is very arcane

undone coral
#

it's part of this very long journey

#

at least if you want to make something that feels as polished as Clash Royale

#

or counterstrike.

#

openmatch doesn't deal with players disconnecting while matchmaking, for example

severe tundra
#

does your system deal with disconnection?

undone coral
#

@severe tundra so for example, what if someone puts in a lobby code, then starts hosting a game, then unplugs their computer

undone coral
severe tundra
#

because one idea i had was just... a huge lobby that was agario but katamari.

undone coral
#

it supports sandbox style multiplayer like that

#

where a game might have 10 slots, and people can join and leave those slots. like a traditional arcade game

#

and once every single player leaves, the whole match resets

#

arcade style matchmaking seems to be what most people want to do anyway

#

that is how the system works by default

#

you have an unlimited number of N player arcade machines, and players eagerly fill open spots in the busiest arcades

severe tundra
#

in my code items have a callable function that just return them to their spawn position and can be knocked off.

so if i had say, a disconnect happens, can i make the player who disconnected just run the code that knocks their items off and returns them?

undone coral
#

yes

#

you get an event for a disconnect

#

they do, after all, really disconnect

#

they close their browser

#

since it's local multipaleyr from an engineering point of view, you don't really "lose" anything though

#

you can author a script that listens for these events and just, does whatever

#

and it will work for everybody

severe tundra
#

ill look into it in a bit, i dont want to learn a whole new thing and encounter whole new bugs as of now...
but if photon ends up still being buggy ill look into mana some more.

chilly talon
scenic forge
#

@chilly talon

#

Though I would agree this is probably not the best use case for SG

#

SG really shines when you need to dynamically generate code in real time while in the IDE, so you don’t need to keep going tabbing back and forth between Unity Editor and your IDE just to retrigger editor scripts.

#

In this case that’s not really being taken advantage of and the ease of editor scripts seems like the better choice to me.

onyx violet
#

hi there
does anyone know how to serialize objects in unity for webgl?
JsonSerializer.Serialize doesnt work on that platform

hushed fable
onyx violet
#

System.Text.Json;

hushed fable
#

There can be IL2CPP considerations when it comes to this stuff, though I saw reports of it working

#

Switch to the newtonsoft json package to make sure IL2CPP is handled

fresh salmon
#

Yeah STJ uses source generators, which might cause issues. But how did you get to use STJ in the first place, as far as I know Unity doesn't use .NET 5 or above

undone coral
#

using system.text.json can add 10Mb or more to your webgl build

chilly talon
#

I tried this, somehow the entire scene turned pink as usual.

#

and gave the same errors that I posted before.

#

And then spams me with 'Allocation of 60 bytes at 00000208E3824210'
Maybe it's a terrible version of Unity.
Gonna check with 2021 LTS

chilly talon
#

Yup, seems like 2022 is just stupid, works in 2021 LTS.

honest hull
#

How do I override this so that I dont have to change this origional code but make it compatable with hdrp?
basically I need to convert this:

 RayTracingShader.SetMatrix("_CameraToWorld", _camera.cameraToWorldMatrix);

to this:

cmd.SetComputeMatrixParam(Shader, VariableName, Mat);

And I wanna do it by having a function called SetMatrix
is this possible?

scenic forge
#

Not touching 2022 until much later then.

teal sage
# honest hull How do I override this so that I dont have to change this origional code but mak...

Yes, it is possible to create a function that sets a matrix parameter on a compute shader using the SetComputeMatrixParam method. Here is an example of how you could do this:

void SetMatrix(ComputeShader shader, string variableName, Matrix4x4 mat)
{
    int kernelIndex = shader.FindKernel(kernelName);
    shader.SetComputeMatrixParam(kernelIndex, variableName, mat);
}

You can then use this function like this:

SetMatrix(Shader, "VariableName", Mat);

This will set the matrix parameter VariableName on the compute shader Shader to the value of Mat.

#

Let me know if it works!

honest hull
#

but I wanna try and keep it as the old function call, wanna keep it as Shader.SetMatrix(VariableName, Mat);

teal sage
fresh salmon
#

(Especially for advanced code, where research is more than expected)

jolly token
#

ChatGPT generated code is not brilliant, FYI

teal sage
regal olive
#

Guys does anyone know how i make the player look trough the right camera in photon pun ? he controlls his own character but looks trough the camera of another player

native beacon
#

Where on earth is that code from? It is kind of a disaster.

#

Why are you using floats for the rows and columns? Do you intend to have fractional amounts?

obtuse remnant
#

Anyone here comfortable with Unity's Runtime Rigging, and has time to walk me through combining an animation with aiming?
(I've got it set up to IK the hand to aim at the target, but it "locks" the hand to the IK position & rotation.
I'd like to be able to turn/move the hands while keeping the movement/pose from the underlying animation.)

agile horizon
#

This is it

#

It should fix it

regal olive
#

i forgot to update you i fixed it like 1hr ago but thank you

agile horizon
#

You're welcome 😁

regal olive
#

i just destroy the other cameras to myself if they arent mine

agile horizon
#

Or just disable the camera component you might relay on camera for something so to avoid future errors disable the camera itself

#

Instead of destroying

keen gyro
#

I'm trying to get a rigged model of an arm to loosely follow the direction of the mouse all ragdoll like. I honestly don't even know where to start

austere jewel
#

Get an acceptable point using a raycast, and use IK to constrain the arm to that point

keen gyro
#

THANK YOU

#

I've been pondering this all day

regal olive
#

I have a first person multiplayer game. I want the player to be able to press buttons too while being able to move their character

How can I do that

When i try it the button is not responding at all

because unity is not considering that as a click

obtuse remnant
placid nest
#

Hello, I have a bunch of images, which need to use the same effect. What is the best way to do this? I tried converting the sprites into a mesh and combining those into 1 main mesh and then putting the material I want for it on there, but I had problems with the size of the meshes. A problem with that is that the image count doesn't stay the same.

How this would work in game is that when it's your turn there's an outline effect over all cards (so the outline of the entire thing) and when you hover over a card only that card gets an outline.

#

This is what I get when I generate meshes from the sprites. It does generate them well, but I can't change the size

severe basin
#

Hi, i have a map game and i want to paint the smaller divisions of the map in a color to represent countries. How do i do that without creating a new sprite for each smaller division of the map?

upbeat path
# severe basin

easiest way
make a list of a pixel point for each division, preferable as near to the center for each division.
then spiral out from that point until you hit a boundry.
once your spiral completes without changing anything your flood fill is complete for that division

severe basin
undone coral
# severe basin Hi, i have a map game and i want to paint the smaller divisions of the map in a ...

you should prepare the asset properly. it will take you much longer to program a solution. use the photoshop importer in unity. open the image in photoshop, use magic wand to select each province, then right click and Layer via Cut. name the layer the province. save as a psb (the modern psd format) directly into your assets folder. set up the importer. you now have each province as a sprite.

undone coral
undone coral
severe basin
undone coral
undone coral
#

it will work fine

#

there are maybe 60 provinces on screen. you can do this in 5 minutes

placid nest
undone coral
severe basin
#

there are like

#

1000 provivces

placid nest
#

ah okay, well I'll take a look for that then

undone coral
#

i guarantee you still faster than programming a solution

#

try to get it to work with a few provinces

#

meaning try to cut out a few provinces

#

and have a working game first before you do the whole map

#

2 hours is nothing

severe basin
#

yeah you are right

#

i will do it

#

ty

undone coral
#

you'll wanna use a more attractive map!!

#

don't actually use this one

#

i mean of course there are vector based maps that already have all the provinces separate @severe basin

#

and will look better

#

unity has an svg importer too

#

so it will generate sprites from a vector file

#

if you do the PSB approach, you have to treat it as a "sprite rig" so that it creates a prefab with everything laid out in the right place

severe basin
#

i will problably change it later tho

severe basin
brisk pasture
#

it would depend on on the svg is constructed

undone coral
#

i would check shutterstock / pond5 for a pre-existing map

#

in vector format

#

and pay the $5 or whatever it is

severe basin
#

the advantage of using a pre made map is that the borders are already laid out perfecly for the intended use

undone coral
vernal frigate
#

Hey I found weird stuff that my brain can't explain why this does happen.
Small back story:
I'm learning mesh rendering and using catlikecoding website for good tutorials. (<https://catlikecoding.com/unity/tutorials/procedural-meshes/square-grid/<link>)
I finished section #1.6. When I did press run I got this error: ArgumentException: Index buffer element #0 (value 1953066581) is out of bounds; mesh only has 4 vertices.
The value is insane. I played around and tried to fix it and stuff. Nothing that I found/test did work.

So I did add this:

        Debug.Log($"Steam 0 stride {_mesh.GetVertexBufferStride(0)}");
        Debug.Log($"Steam 1 stride {_mesh.GetVertexBufferStride(1)}");```

After this:
    Mesh.MeshDataArray meshDataArray = Mesh.AllocateWritableMeshData(1);
    Mesh.MeshData meshData = meshDataArray[0];```

It looks like this now:

    private void GenerateMesh()
    {
        Mesh.MeshDataArray meshDataArray = Mesh.AllocateWritableMeshData(1);
        Mesh.MeshData meshData = meshDataArray[0];

        Debug.Log($"Steam 0 stride {_mesh.GetVertexBufferStride(0)}");
        Debug.Log($"Steam 1 stride {_mesh.GetVertexBufferStride(1)}");

        MeshJob<SquareGrid, SingleStream>.ScheduleParallel(
            meshData, default    
        ).Complete();

        Mesh.ApplyAndDisposeWritableMeshData(meshDataArray, _mesh);
    }```
and some how error is gone. Can somebody explain that insane index value is gone?
vernal frigate
#

what do you mean?

undone coral
#

_mesh.GetVertexBufferStride(0) may have some side effects, but i don't think it does

#

the logs themselves have nothing to do with resolving the issue

#

i think you probably have a different issue

vernal frigate
#

yeah that what I was thinking. I have no clue what is the problem tho.

vernal frigate
#

It is just weird. I have followed that tutorial and checked everything like three times, but still getting this error.

sly grove
#

Don't you actually just want to change the code in UpdateVisibilityOfObject?

#

Or rather

#

Call ChangeBool from GameObjectChanged instead of calling UpdateVisibilityOfObject

#

Or wait sorry

#

If you want to enable/disable the object... isn't the code correct already

#

I don't get what the issue is

abstract sinew
formal egret
#

Can I run code in two different stages of the render stack? aka on two different events, I want something before rendering and another thing after rendering, for example if I put my code inside my renderer feature's Configure(), it doesn't work, however if I place it inside a method subscribed to RenderPipelineManager.beginCameraRendering, on a separate script, it does, however I'd like not to have a script separate from my renderer feature

formal egret
#

Aka I want the same functionality of FrameRenderingStart and FrameRenderingEnd, together, inside a Custom Rendering Pass

#

possible?

sage radish
umbral charm
#

hello peeps, does anyone know how to optimize trees generation on terrain during runtime? I've tried to use threads, but most of the methods are only executable in the main thread

formal egret
#

Okay that's actually smart, so I can basically implement the functionality of a script that has both framerenderingstart and framerenderingend together in one feature

formal egret
formal egret
# sage radish Yep

But then how can I pass variables between the two? I have an offset that needs to be calculated in the first pass and passed to the second one, it can't be calculated in the second one since it would be 0 after rendering

sage radish
formal egret
#

I have a variable declared offset that I can access in both events

#

Aka inside framerenderingstart and end

sage radish
#

You could store it in a static field or give the "before pass" a reference to the "after pass" to set a field, or vice versa.

#

Or create a shared object that's given to both passes that they can access and modify

formal egret
#

Hmm how would I go about the shared object method? Or can i access fields from the feature inside a pass?