#archived-code-advanced
1 messages · Page 196 of 1
If it converts it, is there any plan to support USD natively like Maya or Houdini or some proprietary game engines?
i think everything you need to know is in the documentation here https://docs.unity3d.com/Packages/com.unity.formats.usd@3.0/manual/index.html @nimble lynx
you haven't really expressed your goal. suppose unity could delegate out rendering the layers from maya or houdini. and suppose it could composite the render layers correctly, somehow, with some kind of compositor compatible renders from its own cameras. then what? it wouldn't be real time
so if i were you @nimble lynx i wouldn't stress too much about the USD format. you should export whatever it is you want to use in unity to FBX, and set up the materials in unity
The project is confidential, and I can't share much. We can only use Unity if it supports our USD-based pipeline. I got what I needed for now. Thanks for your help!
i don't think it makes sense to do cinema rendering inside of unity. you would have to do the work of converting your X to Y things that are compatible with a realtime game engine.
Does it matter where I declare my variables in regards a loop and the garbage that could be created?
For example this:
while (true) {
var x = 1;
// do something
}
versus:
int x;
while (true) {
x = 1;
// do something
}
My intuition tells me the second one would generate less garbage and less memory allocations but Im not sure if Unity is doing some optimization when this is compiled
it's happening on the stack, it doesn't matter
thanks
I was asking this because I tried to optimize it but re-sharper complained
so that made me suspect it didnt really matter
thanks for confirming
It pretty much doesn't but having the variable in an outside scope that isn't intending to use it should be avoided whenever possible.
Under extremely tight loops you might get some performance gains by moving stuff like this around, but it's also highly dependent on the system it's running on, how the compiler decided the code ought to be moved around, so it's kinda useless to look at—there's almost always going to be better things to focus on, and memory on the stack doesn't contribute to GC, and is super fast
is it possible to build unity windows standalone il2cpp with clang instead of msvc?
also, is it possible to get the c++ files from a windows build step
instead of going straight to compilation?
just like with ios builds?
I've never built with clang, but my builds with msvc spit out all the cpp files
i've never opened them though, i'm assuming they're obfuscated (unintentionally) .. like hard to read methods and stuff
and there's a bajillion of them
(that's on "light" code stripping)
How can I change the Package.appxmanifest file?
I want to add an entry which I belive unity doesn't support from the player settings:
https://docs.microsoft.com/en-us/windows/uwp/launch-resume/web-to-app-linking
Will this ricochet system work with movement of bullet based on velocity?
the code to change its trajectory looks right. I'm not sure whether or not you are preserving its velocity with the physics system or if it is losing it in the collision
ah yes it is losing its force when collides with border that is why not getting ricochet effect, is that right?
so i need to use trasnform
I literally have no idea, sorry
ok
Hello. I am trying to replicate the mechanics of Fez. The catch is that the character is in a randomly generated world. How would I do this? I am thinking of first pulling of the mechanics (Which I am most confused about) and then making the world generation a thing in a voxel enviroment.
Bump
The answer to your question is about the length of a book
And your question is also not very clear
Hm, how so?
multiple books, in fact
Lack of details, lack of a clear question
you need to split the project into smaller parts and then research or ask about specific things
I've done a bit of research on Fez mechanics in Unity. I've found yet to be helpful code. As I said before, I am thinking of first pulling of the mechanics and then doing everything else. What I meant to ask is how would I theoretically implement Fez mechanics in Unity.
You don't just "pull" off all the mechanics in the game, first get a character walking and implement things in tiny little steps
and ortho camera?
I've done that. I am just confused on implementing the 3D rotation
can someone explain to me what is Accelerometer Frequency? and for what it is used?
probably the number of times per second the accelerometer of a device is sampled (mobile)
Hello folk!
I have this api that retrieves the whole information from the db.
but I'm won't use all the information in the records, just id and org name would be fine
Would it be fine if I omit those fields not necessary for my purpose?
In what
in the response object
I have a lot of field coming as a response, which are unnecessary for this API call
You mean the object you deserialize to?
No the JSON is sent by the server
If you control the server then just send whatever you want
As long as your client handles it properly
yes but I'm trying to understand the best practicies.
in terms of security, I have heard that I must get the data that I need only. But
in another scenario, I will need to have those values as well
If you want best practice advice then you really need to provide more context
hmm. Sure.
I have organizations and courses, and I will add a course to multiple organizations at the same time. to do so, I created a OrganizationsCourses table
this stores the data of 'courseId', 'orgId' and, 'Id' (incremental)
and I have this API above (Get all organizations)
and the API for a course that was owned by organizations.
so in frontend I call this API to get all the organizations and visualize them.
as a result, I put some checkboxes next to the courses and those checkboxes are true if the course is assigned to that organziation.
API will delete all records and put the new values into the database when I make the call.
The question arises here.
Should I remove unnecessary field from my response JSON so it will be clean and properly in terms of security
So, it's probably not that big of a deal since it's pretty insignificant data either way, if you were including PII data in those requests then you don't want to query the PII data if you don't need it
It sounds like, based on your description, that you can just cache the data initially which makes it so that you don't have to make multiple requests
There are also some solutions like GraphQL which let you specify which fields you want in your request
It's probably overkill for what you need
Is it possible to embed a Unity application inside a second Unity application as a library? Sorry for asking a let me Google that for you question in code-advanced but just wanted to see if anyone knew off the top of their heads.
i think fez is fully 3d, as is the character, and the character instantly teleports along z with a bajillion exceptional rules
it was designed iteratively depending on the puzzle
i think he might also be on a foreground layer sometimes
it sort of does it all
like on a separate layer from the 3d world
you can also email the guy and ask
👋 Howdy all. I'm new here (so apologies if this is the wrong place). I'm attempting to add a Source Generator to a Unity project that needs access to some Additional Files (which are normally specified in a csprojfile, e.g.: <AdditionalFiles Include="Foo/Bar/*.asset" />). Is this a thing that is possible at all, or is there some other workaround?
what is the source generator?
everything you need to know is in the documentation - https://docs.unity3d.com/Manual/roslyn-analyzers.html
@undone coral so, i've dug through there and didn't see the answer to my question. Am I missing the part about configuring additional files?
(or a bit that says "you can't do that, manually use System.IO", or something?)
you can try https://github.com/Cysharp/CsprojModifier
re: "what is the source generator": I threaded some extra context here: #984827329635315812 message
oh shoot. this looks great.
tyty
i think that project is exactly what I need. But: i'd still love to hear if there is a "recommended way" of generating source files from asset files that i've just missed. I'm basically trying to follow this cookbook example with Unity Asset files: https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md#additional-file-transformation
I have this class:
public class PlayerHand<T> : LinkedList<T>{
private bool IsItemMatching(T component)
{
component.Equals(First);
}
}
Also this extension method i've ripped from the internet:
public static int IndexOf<T>(this LinkedList<T> list, T item)
{
int count = 0;
for (LinkedListNode<T> node = list.First; node != null; node = node.Next, count++)
{
if (item.Equals(node.Value))
return count;
}
return -1;
}
And i'm using both of these on a class with this override:
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null)) return false;
if (ReferenceEquals(this, null)) return false;
if (obj.GetType() != GetType()) return false;
return ((GameTile) obj).tileType == tileType;
}
Is there a way for me to change that extension method so instead of equality it checks whether they're identical.
Why?
sorry i sent that too soon
object.ReferenceEquals(a, b) will check for objects being the same object in memory
well i'm dumb... and i even had it on my equals override, thank you.
Do you agree using enum values and implement logic based on these values is not a good approach?
If the values change, logic in somewhere in the code will be totally wrong
// Do not change the values never ever!!!
public enum RotationType : byte
{
Rot0 = 0,
Rot90 = 1,
Rot180 = 2,
Rot270 = 3
}
uvs[(j+(byte)rotationType)%4]
My way is to define Enumeration class with explicit field index for example.
What is your opinion?
public class RotationType : Enumeration
{
public static RotationType Rot0 = new RotationType(0, 0, "Rotation 0");
public static RotationType Rot90 = new RotationType(1, 90, "Rotation 90");
public static RotationType Rot180 = new RotationType(2, 180, "Rotation 180");
public static RotationType Rot270 = new RotationType(3, 270, "Rotation 270");
//...
}
Seems a little overkill
I've made enum classes like this before, but they are limited. Because the values aren't constant, you can't use them in switch, which is pretty bad.
public enum Rotation {
Rot0 = 0,
Rot90 = 1,
Rot180 = 2,
Rot270 = 3
}
public static class RotationExtentions{
public static int Degrees(this Rotation r) {
return (int)r * 90;
}
}```
generating C# source files => no
generating anything else => asset importer
Could you not just set the rotation value in the enum and cast, then you dont need to do multiplication
you could sure
Is the only way to call a constructor from another constructor in curly braces by making an initialize method?
you can call a constructor from another constructor just fine with or without
Thanks, but I meant calling constructors in the same class
show what you mean
public DisplayNameBody(string[] inputs)
{
if (inputs.Length == 4)
{
Initialize(inputs[0], inputs[1], bool.Parse(inputs[2]), float.Parse(inputs[3], CultureInfo.InvariantCulture.NumberFormat));
}
else if (inputs.Length == 3)
{
// skippable is false
Initialize(inputs[0], inputs[1], false, float.Parse(inputs[2], CultureInfo.InvariantCulture.NumberFormat));
}
else if (inputs.Length == 2)
{
// no autoskip and is skippable
Initialize(inputs[0], inputs[1], true, -1f);
}
}
private void Initialize(string dialogueName, string dialogueBody, bool skippable, float time)
{
this.dialogueName = dialogueName;
this.dialogueBody = dialogueBody;
this.skippable = skippable;
this.time = time;
}
I have a class that takes in an array of strings as input
Depending on the contents of that array, I would like to call a different constructor
Instead of "Initialize", can I use a constructor?
Right now all my constructors just the arguments into Initialize
there's probably a way to call the constructor again with reflection but you should probably just include the Initialize method, yeah. ```cs
public class MyClass {
public int value;
public MyClass(int value) {
this.value = value;
}
public void Initialize(int value) {
this.value = value;
}
}
I see, thanks
ah, i see what u mean now, yea i'd agree w Tecci just to keep it
u can clean up the constructor if u want tho
public DisplayNameBody(IReadOnlyList<string> inputs)
{
switch (inputs.Count)
{
case 4:
Initialize(inputs[0], inputs[1], bool.Parse(inputs[2]), float.Parse(inputs[3], CultureInfo.InvariantCulture.NumberFormat));
break;
case 3:
// skippable is false
Initialize(inputs[0], inputs[1], false, float.Parse(inputs[2], CultureInfo.InvariantCulture.NumberFormat));
break;
case 2:
// no autoskip and is skippable
Initialize(inputs[0], inputs[1], true, -1f);
break;
}
}
Not a big fan of switch statements because of the breaks
ah
There also mnight be instances where the lengths are the same but the types are different
Yes you can have constructors call other constructors
How do I do it?
public class Example {
public Example(int x, int y) {}
public Example(int x) : this(x, 5) {}
}```
Hot take here since many disagree w this but when i do if else statements and its only 1 call
I prefer to do
if (something)
DoSomethingElse();
else
DoSomethingEntirelyDifferent();
similar to
if (!something) return;
// or
if (!something)
return;
constructor overloading is what Praetor is doing
Ah I see, but the this(...) happens outside the curly brace. Would it be possible to have a version of that in the curly braces?
Since I would like to do some logic before calling the other consturctor
no it doesn't work that way
it must be the first thing called
I see, so it's like Java
Similar to-- yes exactly
Seems like Initialize is the only way
Just different syntax
Does anyone have advice on how to structure code in Unity projects so it doesn't become a huge mess of spaghetti instantly?
Organize it into folders and namespaces. When it gets big enough you can even break it up into multiple assemblies
I dont think theres one advice that would give you clean code. learn code organization, data structures, oop concepts
the issue is that standard OOP doesn't seem to map well to Unity scripts
How so?
correct
Unity is a GameObject/Component architecture
you should not be relying heavily or primarily on inheritance/polymorphism
focus more on composition of components
Yeah thats true. Things like interfaces can still make huge difference to your code cleanness
I mean you often have to deal with lots of components and concerns at once (for example: Input, Physics, AI, all in one function) and it gets messy for me.
I'll just give an example I just wrote
private void HandleInput()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100,
Physics.AllLayers, QueryTriggerInteraction.Collide))
{
var healthComponent = hit.collider.GetComponent<HealthComponent>();
if (healthComponent != null)
{
// Attackable.
SelectTarget(hit.transform, healthComponent);
destination = target.position;
}
else
{
UnselectTarget();
destination = hit.point;
}
}
}
else if (Input.GetMouseButtonUp(0))
{
UnselectTarget();
}
else if (!hasTarget && Input.GetMouseButton(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100,
Physics.AllLayers, QueryTriggerInteraction.Collide))
{
destination = hit.point;
}
}
}
this is really messy imo but I don't see a way to make it any simpler
it's Diablo 2-like click to move/attack
or maybe I'm off-base
maybe this is not that bad ^^
Thats quite many indents
honestly doesn't look that bad to me
you know you don't need to declare RaycastHit hit; in its own line?
out RaycastHit hit works inside the parameter list
I'd also recommend TryGetComponent instead of GetComponent for a cleaner way to check for that component
var healthComponent = hit.collider.GetComponent<HealthComponent>();
if (healthComponent != null)```
becaomes
```cs
if (hit.collider.TryGetComponent(out HealthComponent healthComponent))```
ah I didn't know that one thanks
Any clean code enjoyer would split that into million smaller functions and always return early so you never need to use else keyword but that doesnt look that bad (compared to my code atleast) for me eather
alright thanks ^^ good to know it's readable for other people
I figured it'd be hard to understand what's going on here if I had to look at it again in 2 weeks
but I guess you can't always avoid that exactly
actually nevermind it's quite simple
I don't know why I'm stressing so much
when I write code in non-game projects, I often don't need that many branches/indents, and rather early return etc.
makes stuff easier to read imo
i have recently aimed for the "don't use else" thing and I really love it
it's obviously just a stylistic thing but i really just like that my code has become, in general, much less indented overall
hot take: style
if & return on same line 👀
How can I check if an action is going to happen? Let me explain.
Okay, so, I have this 3D rotation system (like Fez), and I want the player to not be able to rotate if the player is going to fall when rotated. How would I do this?
that's... quite a complex question
it really depends on the details of your system
Let me record a video (and send the code if wanted)
While I try to record a video, I want to say that my system basically freezes the players y position when rotating and then rotates the whole level
So it's just 3D physics the whole time?
Yep
You could basically copy the scene into a separate physics scene - rotate the level there and do a raycast
or boxcast/capsulecast
and see if there's anything below the character
How would I basically copy the scene into a separate physics scene?
Could also just rotate the level - sync transforms - do the raycast/boxcast - then rotate it back - sync transforms again
without anyone being the wiser.
if that works it's simpler than introducing a separate physics scene
Wouldn't that be noticable though?
why>?
You would do everything within a single frame
by the time the frame renders everything is back where it belongs
there would be nothing to notice
Oh alright
My current code is ```csharp
IEnumerator TurnLeft()
{
var fromAngle = cubes.rotation;
var toAngle = Quaternion.Euler(cubes.eulerAngles + (Vector3.up * -90));
for (var t = 0f; t <= 1; t += Time.deltaTime / 0.8f)
{
cubes.rotation = Quaternion.Slerp(fromAngle, toAngle, t);
yield return null;
}
cubes.rotation = toAngle;
rotating = false;
}
IEnumerator TurnRight()
{
var fromAngle = cubes.rotation;
var toAngle = Quaternion.Euler(cubes.eulerAngles + (Vector3.up * 90));
for (var t = 0f; t <= 1; t += Time.deltaTime / 0.8f)
{
cubes.rotation = Quaternion.Slerp(fromAngle, toAngle, t);
yield return null;
}
cubes.rotation = toAngle;
rotating = false;
}
alright
I have no idea what that is
pseudocode:
TurnRightInstantly();
Physics.SyncTransforms();
bool mayRotate = PlayerPositionIsValid(); // do the raycast in here
TurnLefttInstantly();
Physics.SyncTransforms();
if (mayRotate) {
StartCoroutine(TurnRight());
}```
When you move objects via the Transform, those changes don't get synced to the physics engine instantly
it will get synced only during the next physics simulation step (FixedUpdate basically)
If you want to do raycasts for example against the new state of the world after moving something without waiting, you need to sync it manually
Now uh, another question
I am kind of not good at raycasting
Hm, maybe not
I'll figure this one out myself
It works perfectly, thanks
Yo! Does anyone know of any .net core networking libraries that let you make an async websocket (tcp/ssl) server? I want to make a server for a webgl client game. I want to write it in C# and not nodejs/etc because I want my client and server model to share core classes for communication.
I've looked for a couple of days but I can't find what I'm looking for. I might just be really bad at using google, Lol
I'm not really familiar with networking/async code so maybe this isn't what you are looking for, but is this helpful? https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-6.0
Learn how to get started with WebSockets in ASP.NET Core.
example code seems to dispatch requests asynchronously
SignalR looks like it would be good for game communication.
Alright, so. I have a 3D rotation system which blah blah blah... Read it all up in the replied message.
I want my player to be able to jump up to the top platform from the bottom platform
Here's how it looks in 3D space
Oh, btw, I've change the 3D Rotation code so that only the camera is rotated, and not the whole level
Bump
I dunno if this is incompatible with your approach, but i'm using Ruffles rUDP (managed C# library for reliable udp) and a shared DLL library for my multiplayer game, and it works pretty well although there's a bit of a learning curve
(i'm also using MessagePack for C# to serialize the messages into tiny little byte streams)
web browsers do not allow for communication through udp and instead use websocket/tls protocol
so unfortunately no it would not be viable
Ah, didn't know that
A quick google on it gave me a little bit of a finger-wagging too:
Short answer No. I would simply close this as a duplicate of the many times this has been asked here before, but the answers elsewhere are surprisingly poor. The security problems are rather over-stated - it would be trivial to prevent amplification attacks that have proved troublesome with DNS and NTP. The reasons I am aware of are that 1) its not needed for most of what a browser does currently 2) its very difficult to implement across the internet due to NAT.
and even the IPV6 implementation of ruffles uses UDP so.. looks like it's incompatible, sorry!
https://github.com/MidLevel/Ruffles/blob/master/Ruffles/Core/RuffleSocket.cs#L507
it'd be nice if there were an analogue to rUDP for TCPIP, there's some nice features in it. The guy who wrote it actually was hired by Unity to work on their networking stack MLAPI, so maybe you'll have some luck checking that out, I haven't seen their progress in the last few months. I know they have a discord going, if you're not already in it
i'll check out the MLAPI library
though it'd be nice if i could find a framework that gives me control over lower level protocols while not forcing me to reinvent the wheel for everything
right? there's a lot of sweet features in rUDP.. hashcash challenges, connection pooling, fully managed so building isn't a pain in the ass, MTU for large datagrams, etc
If I knew more about networking and .. had a month to spare, it'd probably be a fun(?) exercise to write a TCP library similar to rUDP
haha we had to write a rUDP implementation in uni recently
for our final assignment in networking
that sounds like a serious project
with error handling for shit like corruption, lost packets, etc
everyone had to do it Looll
it wasn't super huge
i suppose i wish i had that knowledge but also, not. 🙂 It's nice to be able to just say NetworkManager.SendData() and not worry too much about implementation details
just a 'make a reliable transport protocol on top of udp that handles lost packets, corrupt packets and has timeout functionality'
i agree
we were doing this in c too so its not as annoying like in .net where u have all these high level abstractions for low level protocol access
call me a grumpy old man, I did the C thing in highschool, have no desire to ever go back. Dot net for life throws up gang signs
(this was 1994, i'm old now)
Lool cool
im 96
i think C is simpler because it doesn't have a crap load of abstractions on top of abstractions
fair enough
but i think c# is comfier to use in most cases
after youve learnt what the api ur using does
kek
It's nice to be able to get at the guts of the matter, but .. I suppose I rarely need to ever do so.. Sometimes I poke at https://referencesource.microsoft.com/ but usually only out of curiosity
a year ago I didn't even use LINQ expressions/extensions and now I'm like.. totally on the LINQ train
I was like, fuck that, gimme a for loop any day of the week.. now I'm all like Select().where().This().Is().Awesome().ToList() ya baby
Does anyone have a contact at Unity for problems with the new Bug Reporting system (it's broken, I believe I know how/why - it's a known bug in Atlassian, which I thought they'd fixed by now)?
(after carefully looking through all the channels this one seemd most likely to have someone who might know!)
[Key(0)] public HashSet<UpgradeType> TemporaryUpgrades { get; set; } = new HashSet<UpgradeType>();
[Key(1)] public HashSet<UpgradeType> PermanentUpgrades { get; set; } = new HashSet<UpgradeType>();
A year ago, doing a union of these structures would like 10 lines of code, two loops, with a temporary hash set.. now it's just
[IgnoreMember, JsonIgnore] public HashSet<UpgradeType> OwnedUpgrades => TemporaryUpgrades.Union(PermanentUpgrades).ToHashSet();
Hm.. not I. I have been frustrated with the bug reporting process from unity in the past as well. It asks me to log in, I try to log in, login fails, my desire to fill out bug report drops to zero, etc
that's nice, but i thought union would just be like ```cs
//pretend these have items
HashSet<T> a;
HashSet<T> b;
foreach (T item in b) {
a.Add(item);
}
i don't want to modify a though
oh right
i mean, nbd, declare a new tmp hashset, add all of a, add all of b, no problem, it's not hard
just saying it's a lot shorter with linq 🙂
yeah
i'm also really into the whole Max() type things
yeah the max and min things are cool
sad that you gotta make your own MinBy and MaxBy methods tho
since unity doesn't seem to have them for whatever reason
wait, there's no key selector predicate for max() and min()?
nah
🤯 i feel like I should know that but i haven't experienced it
lol
👀 OrderBy().FirstOrDefault()
lol i looked through my codebase for where i thought i'd be doing a maxby or whatever and.... that's exactly what i'm doing
🤔
ah wait i think it was something like
it returns an int instead of the object you want
I have a hard time wrapping my head around the Linq stuff, a little different from the fluent API I use in java at work (which feels more intuitive to me)
i don't use the old school LINQ stuff for expressions, i just meant the extension methods
just the .. things that turn 4 lines of code into 1
Max() OrderBy() Sum() etc
just for practice I tried writing an extension for this, never wrote an EnumerablExtension before:
public static class EnumerableExtension
{
public static T MaxByKey<T, S>(this IEnumerable<T> source, Func<T, S> keyFn) where S : IComparable<S>
{
if (source == null || !source.Any())
return default(T);
return source.Aggregate(source.First(), (max, next) => keyFn(max).CompareTo(keyFn(next)) <= 0 ? max : next);
}
}
pretty cool that it just works as long as the namespace it is in is used
yeah.. I have pretty much all my unity projects with a unityutilities class
i wonder, could i use asp.net core signalR to make an mmo websocket server
and then send and receive data through websocket from a unity webgl client
Is there a nice way to get every element in a grid in a float radius of a point?
I want to get the elements based on their nearest corner to the point.
I can think of ways to do it but they all seem kind of ugly.
i guess you could just loop from x - r to x + r and y - r to y + r and check if x * x + y * y < r * r and if so add it to an array, and after that return it or smtn, probably some edge cases that need to be handled but that's what i'm thinking
This is where it gets a bit complicated, each cell represents a point in world space, so the radius + position will be in world space, meaning things get a bit funky to convert between. Additionally I want get any cells that are touching the circle even a bit, and not just the center.
I also haven't seen the x * x + y * y < r * r before, interesting. I will have to think about it more to understand what it is doing.
its the equation for a circle
well technically the equation for a circle has =
but with < its just every point inside the circle
i.e every point within the radius
Yeah, that tracks. I am not great with math and generally just don't learn much until I have a need for something. (Clearly that backfires sometimes...)
Bump
Good morning everyone. I'm trying to figure out how to implement my skin swapper.
As of right now I have a skin library asset that holds my skins and I managed to develop the swapper properly while I keep the changes in game as well.
The thing is that now I need to have some skins that are available and some that need to be purchased first.
There are two approaches that come in mind for now.
- One that i hold all the skins in a huge sprite library holding all the resolvers and in parallel with a Dictionary that signals which are bought and wich are not I allow or not hte usage of the skin.
Orrrr - The second Idea is to hold several skin libraries and then whenever the user buys a skin, then somehow merge the main library with the skin's one. Or somehow add the new resolvers labels etc to the main library. What is your suggestion? 🙂
Hey, how do you implement something like variable attack speed?
It seems pretty much impossible to access the current state in the animator and change its speed, so apparently you have to change the entire Animator's speed, and then revert it back at the end of attack animation?
nevermind I didn't see there is a speed multiplier I can override per state
I made a visual effect and am wondering, how to turn it on/off in script
any ideas?
not a particle system
I'm sorry but how would x * x + y * y < r * r work? The cells to the right of the point would always be more and the ones to the left would always be less than.
i dont know what you mean
That requires it to go from -1 to 1, no?
(Or some negative number to an positive number of the same value)
ah right right this is for any point
it should be (x - h)^2 + (y - k)^2 < r^2 with h and k being the coordinates of the point then i think
Ohh, well I guess I could just get the cell index and then offset it
Alrighty, thanks I will mess around with it 🙂
According to person on the internet, apparently its much faster to do:
return new Vector3(
f0*p0.x + f1*p1.x + f2*p2.x + f3*p3.x,
f0*p0.y + f1*p1.y + f2*p2.y + f3*p3.y,
f0*p0.z + f1*p1.z + f2*p2.z + f3*p3.z
);```
than doing:
```cs
return f0*p0 + f1*p1 + f2*p2 + f3*p3;```
Anyone know why?
pX are Vector3
fX are floats
I assume because the second one creates a new Vector3 for each operation.
However idk about 'much faster'. That kind of depends how many times you are calling it I guess.
Ah yeah I can see that I think
second one creates a lot of new Vector3s because of the operations
i think there's like 7 in the second one
4 multiplication and 3 addition?
ye something like that
well
the 4 multiplication and 3 addition
are actually 4 * 3 multiplication and 3 * 3 addition
so 12 + 9
21
Ah
All the vector operations are just this
return new Vector3(a.x * b.x, a.y * b.y, a.z * b.z);
it's purely faster because of the new Vector3s every operation
otherwise the amount of float operations are the same
i've dabbled in them a little
i guess cubic would do
Alright now do you know how to find P1 and P2?
If you are on 2022.1+ you can use Unity's new Spline package btw
🤔 interesting
shouldn't you already have the points
hmm
The spline is really nice imo.
In this video Sebastian shows how to auto set the control points. Idk what you are wanting exactly so maybe this will give you what you want https://www.youtube.com/watch?v=nNmFLWup4_k
Source: https://github.com/SebLague/Curve-Editor
Support the creation of more gamedev tutorials:
https://www.patreon.com/SebastianLague
https://www.paypal.me/SebastianLague
Ill take a look
If t=0 at P0
Would t=0.25 at P1?
So:
if P = (1-t)P1 + tP2
Then :
P0 = 0.75P1 + 0.25P2
P3 = 0.25P1 + 0.75P2
P1 = P0/0.75 - P2/3
P3 = 0.25(P0/0.75 - P2/3) + 0.75P2
P2 = 2P3/3 - 2P0/9
And from there I can get P1
i don't bother with that whole math thing i just use Vector3.Lerp a bunch
like ```cs
public static Vector3 Quadratic(Vector3 a, Vector3 b, Vector3 c, float t) {
return Vector3.Lerp(Vector3.Lerp(a, b, t), Vector3.Lerp(b, c, t), t);
}
public static Vector3 Cubic(Vector3 a, Vector3 b, Vector3 c, Vector3 d, float t) {
return Vector3.Lerp(Quadratic(a, b, c, t), Quadratic(b, c, d, t), t);
}
haven't done it in a long time
Does that do the same thing?
Well anyways I got this working pretty much perfectly, just need to add some randomness now:
IEnumerator C_BezierMove()
{
float elapsed = 0;
float dur = 1;
Vector2 startPos = transform.position;
while(elapsed < dur)
{
Vector2 p0 = startPos;
Vector2 p3 = Player.Instance.transform.position;
Vector2 p2 = (2f * p3 / 3f) - (2f * p0 / 9f);
Vector2 p1 = (p0 / 0.75f) - (p2 / 3f);
transform.position = Extensions.BezierCube(p0, p1, p2, p3, elapsed / dur);
elapsed += Time.deltaTime;
yield return null;
}
Player.Instance.GoldCount++;
}```
nah i looked at your thing too quickly xd
lol
Is there a better way to get a random sign? This is kind of chaotic:
int RandomSign = Random.Range(0, 1) < 0.5f ? -1 : 1;```
Wait
Got it
float RandomSign = Mathf.Sign(Random.Range(-1f, 1f));```
and to answer the question, probably not
What does Mathf.Sign(0) return?
Oh good
Looks like RandomSign * P2 & P3 completely breaks it
Oh wait duh of course it does
How do I get the a point symmetrically flipped across another point
Guess its time to reverse engineer the midpoint formula again
guys
just a question
should i recycle one commandbuffer for all instances
or i can make multiple ones?
(performance based)
C#/VB/F# compiler playground.
obviously no aggressive inlining which is what unity uses, and also using ints instead of floats, but you can see just the number of IL calls is like ... 10x as many for Slow()
maybe it's not as obvious since the operator* and + are hard to untangle - but there's 7x of those calls (versus none for the fast implementation)
Does anyone know why my visual studios says miscellaneos files instead of assmebly csharp
because your intellesense(unity autocomplete) isnt working
if found the solution via reddit
ya same thing was happening to me and i found a youtube video on it
i didnt have it set at my external script editor
ya there were also other solutions
can you help me with this pls
how do i add art to a game object if it already has been coded?
why doesnt this work and how do I make it work? If I run it, unity yells at me that I cant set randomwrite enabled to an already created texure, but if I try to feed it to a compute shader to write to it, suddenly its not randomwrite enabled?
Im about ready to start making like 20 rendertextures per frame for temporary textures isntead of using temporary textures...
for(int i = 0; i < 5; i++) {
RenderTexture Intermediate = RenderTexture.GetTemporary(TargetWidth, TargetHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
Intermediate.enableRandomWrite = true;
Intermediate.ReleaseTemporary();
}
If I use .Release it doesnt yell at me, but then after awhile I believe it causes the asset ID to go out of range so thats not an option
can you recycle rendertextures instead?
pool them yourself?
should be easy enough right?
instead of temporaries
trying that but im running into an issue with not evenly dividing by 2(tryng to do bloom so I need to downsample and upsample
oh the reason why I cant really recycle them is cuz each time its a different size
and the size is different every time basically(due to int divisiono)
this is disgusting is there a better way to get value of toggle group on change?
i suppose you could do a for loop
but the forloop would work once
and cache toggleGroup.GetComponentsInChildren<Toggle>()
?
they dont click a button to confirm which one is active, it is used to actively change search results
i'd need an on value changed for each one?
like that would work if this was possible, then i'd just call something to check
but you need to check each individual element for on value changed to get anything
unless theres some other syntax i dont know about or im not understanding what youre saying
i was talking about doing a for loop and caching to make it look cleaner, which is what i assumed you wanted. ```cs
var toggles = togglegroup.GetComponentsInChildren<Toggle>();
for (int i = 0; i < toggles.Length; i++) {
//capturing
var _i = i;
toggles[i].onValueChanged.AddListener((bool on) => NarrowSearchLanguage(_i));
}
that makes sense. I wonder why they dont just have something like this
i appreciate it though
yeah i'm looking at ToggleGroup rn and i don't see any reason they wouldn't have a function to add a listener to every toggle
seems pretty easy to make as well ```cs
public static void AddListeners(this ToggleGroup toggleGroup, Func<bool, int, void> f) {
//this part seems like something that could be optimized but idk
var toggles = togglegroup.GetComponentsInChildren<Toggle>();
for (int i = 0; i < toggles.Length; i++) {
var _i = i;
//not sure about this part
toggles[i].onValueChanged.AddListener((bool on) => f(on, _i));
}
}
i'd guess just few enough people use it they havent done something like this
or they forgot? idk
lmao
lol
toggleGroup.GetComponentsInChildren<Toggle>().ElementAt(langaugeIndex).ToString().Split(' ').First()
to get the value of the one actually selected lmao
after it goes into NarrowSearchLanguage
For what? 3D text based on TMPro? Feel like I've seen one around that does that
Ah, this is the one I was thinking. Not TMPro, but might be what you're after. Not sure https://assetstore.unity.com/packages/3d/gui/modular-3d-text-in-game-3d-ui-system-159508#description
Okay, how do you convert a world position to a grid position?
I thought it was this. But it only gives even grid positions.
x = (int)(Mathf.Round(position.x / _cellSize) * _cellSize)
You just don't multiple it after... I got too deep in to it...
I think I was able to do something like this with the underlay component of a tmp text, but it was limited in the amount of depth you could get out of it
how about a good input system virtual joysticks asset?
How do you force the size of a created atlas texture? I need to pack them into a texture2darray but for that they need to be the same size
WAIT TEXTURE2D's ONLY SUPPORT UP TO 2 GIGS??
MMO&RPG UI has a nice virtual joystick in it
Idk but isnt that a lot already? That would eat huge portion of the vram when used for rendering
yeah thats fair but I am gonna have to end up upscaling all my textures to like 4k just to make sure I dont lose detail on the high detail ones while still being able to send them all to the GPU compute shader at once
Isnt 4k still way less than 2 gigs?
which is a problem if I also have hundreds of small textures
simply atlas'ing them all is now too slow with the amount that I need to be able to handle
if I could just have the atlas create a fixed size that would be nice
You are the one writing the math for the texture atlas. Set it to anything you like, no? If it overfills, split it to another texture. I'm not sure where the question is in that statement though.
Hard to give you more advice though as it depends on how you are bringing textures into the array at the onset
Unity cannot bake dynamic GameObjects into the occlusion culling data. A dynamic GameObject can be an occludee at runtime, but it cannot be an occluder.
whats the difference between occludee and occluder?
my guess is that an occludee is something that can be culled while an occluder helps unity determine what should be culled
just going off of how english works
my character controller is not working it has the capsule collider and the camera is a child object of the player which right now is a cyllinder
hello i am workling on a code via a yt video and i came across this character and dont know how to type it
its the character next to the void player movement()
nothing ?
it isnt a character or
whats a qwerty keyboard
keyboard layout
idk let me take a pic of my keyboard
😐
heres the pic
oh boy i wonder if this is a qwerty keyboard
I am gobsmacked that we're in #archived-code-advanced
oh now i get what you mean by this
i was in bgginer and no one could help me
Yes the magical character in the code is just a collapsed method
In the future, stay in #💻┃code-beginner where your questions belong.
💀
Hey 👋
Is there any way to get dispose called on a class once you exit playmode?
Calling GC.Collect manually once playmode changes doesn't seem to cause it to get called? I've tried both with a destructor and with IDisposable
are you wanting it to be disposed automatically?
unity doesnt call those functions normally so youll have to write an editor script to do that
I've done that by subscribing to playmodestate change, calling forced Collect on all generations
GC.Collect from what i know doesnt call dispose on an object
it should call the deconstructor if its considered garbage
Shouldn't it be considered garbage if playmode is done?
unfortunately unity doesnt mark everything as garbage when switching between playmodes
it just destroys scene objects and components
so you would need to call dispose in the hook function in order to properly destroy it
Any way to dispose of runtime instances manually?
unless you can call dispose (or destroy if inheriting UnityEngine.Object) theres not much you can do unless you can remove their references (which will mark them as garbage)
Ask in #archived-shaders as this isn't a code issue
true
ik i didnt realise but i get it now
what's the best way to project a wide stroked line onto terrain / other colliders?
drawing onto surfaces, but also with mitered/proper caps (unlike line renderer)
my goal is to make a character moving around a terrain that leaves a graphic trail on the ground
why my tower shakes like that when i move. my tower rotation is based on plane.raycast
https://gyazo.com/b8d663e8f08c50e5eb92a85ea73d6e29
{
Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
Plane plane = new Plane(Vector3.up, Vector3.zero);
float hit;
if(plane.Raycast(ray, out hit))
{
Vector3 pointToLook = ray.GetPoint(hit);
Debug.DrawLine(ray.origin, pointToLook, Color.red);
transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
transform.eulerAngles = new Vector3(-90, transform.eulerAngles.y - 90, 0);
}
}```
and to move my tank im using rigidbody.MovePosition
should i use transform movement?
OnApplicationQuit and use a check if its editor within?
if the class is non monobehaviour create a list which holds reference to all such classes, and call dispose from a monobehaviour script as mentioned above
i used transform movement now it is not shaking
are scrollbars supposed to be unfixable
i dont think ive been able to fix a single broken scrollbar
i just restart
If I have an asset thats a model and not in the hierarchy yet, is there a way for me to auto-remap the materials from script?
using a webgl build, why does unity not respond when the player hits escape to get cursor control back? i have an update loop checking for ESC and it doesnt fire when the cursor is locked on a webgl build
does anyone have ideas for better rotation in regards to AR or even positioning
like how would I got about having an object spawn at an object then add an offset position to it
is there something special i have to do to set values on a script from a ContextMenu?
also the PositionConstraint editor is so insanely glitchy
i feel like i'm taking crazy pills. if the weight is 0, the position constraint should not move the transform even if it is active. why does it evaluate otherwise
All objects will be cleaned up upon an assembly reload, Unity reloads assemblies when starting play mode but not upon exiting it; probably as an optimization.
One way to reload assemblies is to enforce a Script Compilation Request from the Compilation Pipeline.
This might slowdown your project considerably tho, it'd probably be faster to just hook into the play mode change event and clean up only what you need
Make sure both your tank and the camera has moved before you run that logic. Those sort of issues are often caused by using data that is one frame out of date (due to order of execution).
its just basic vector math you're dealing with.
Instantiate with pos and rotation parameters.
then just add x or y or z to position based on the type of offset you need.
same with rotation
Hello. I have a list of 10 elements.
Another list has some of the same items in it.
I want to compare these two lists and change the isExisted property of the first list if the second list item matches
Is it possible to make it in Linq
Sure but it's likely less inefficient than raw code
If they're the exact same items and reference types:
foreach(var elem in list1.Intersect(list2)) elem.isExisting = true;
uh my camera's update method is LateUpdate and Tank is just an Update
but i already fixed it using transform based movement
Hi, I'm using an API through a wrapper which handles requests through async methods. I'm having an issue where, when making a request: I call the wrapper method and it returns a Task<TResult> object. However, when trying to access its result through MyTask.Result, the debugger returns a 403 error. Any idea how to fix it?
And yes, I'm using a valid API key
if it's returning 403 seems like something is wrong with authentication
403 = forbidden
var api = RiotApi.GetDevelopmentInstance("Valid API Key here");
var summoner = api.Summoner.GetSummonerByNameAsync(RiotSharp.Misc.Region.Euw, "Valid Summoner Name").Result;
var matchlist = api.Match.GetMatchListAsync(RiotSharp.Misc.Region.Euw, summoner.AccountId);
The first request is validated, meaning the key is indeed valid, however, the second will return a 403error if I try to access its content, for example :
var api = RiotApi.GetDevelopmentInstance("Valid API Key here");
var summoner = api.Summoner.GetSummonerByNameAsync(RiotSharp.Misc.Region.Euw, "Valid Summoner Name").Result;
var matchlist = api.Match.GetMatchListAsync(RiotSharp.Misc.Region.Euw, summoner.AccountId);
var test = matchlist.Result; // This returns a 403 error
I'm a newbie when it comes to API requests and async methods, but shouldn't the matchList variable be local? Why would I get a 403 error trying to access its contents?
shouldn't you be await-ing in there
it looks like you're trying to get the result without first waiting for the auth call to complete
try var api = await RiotAPI.GetDevelopmentInstance()
no wait, that one's not async
but use that for the Async calls
this might be helpful: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/await
How do you know the first request doesn't return a 403 response if you don't access the results?
Well, it doesn't return a 403 BECAUSE I don't access the results lol
@pale zinc Thanks, I think that's simply the issue, although the provided examples didn't seem to bother using async/await, so I'm a bit confused
That doesn't make much sense. If a tree falls in the forest, it still falls, even if there's no-one to see it.
By accessing .Result in the last line, the thread is blocked until the Task completes
It's one way to not await the task, and do the request synchronously
yeah you should probably check if summoner doesn't also have a 403
Well, it would halt execution if it did, but no, I wrote some Debug statement and all of the information matches, names, ids,...
Ah I think I see why
You don't await or get the result of your summoner Task before feeding it to GetMatchListAsync, in this case I'm not sure what would happen if the task hasn't finished
Ah no I'm just blind
Ignore me
is it possible you're not allowed to call that method with that account id?
Shouldn't be the case. I retrieved the id from summoner and used it on the API's official website to make a direct request, using the same API key, and got a valid response
sounds like a question for whoever wrote the API library
Yes, I submitted a request, I should have the latest version but you never know
Thanks for thelp!
@pale zinc @fresh salmon Okay, turns out the issue was that you needed to use an alpha release to get access to the current API, so there wasn't anything wrong with the code itself, just an obsolete API
Thanks for the update!
I do not want to use switch/case for that!
See, it is just used instead of indices 0,1,2,3.
I mean instead of passing meaningless values 0,1,2,3, you pass RotationType.
Now, why I say enum is bad here because a developer can change the values easily while changing values causes bugs in logic.
Values are used as index uvs[(j+(byte)rotationType)%4] rotationType=0,1,2,3
but if I use Enumeration class, I can add a field with specific name index.
Generally, I think using enums when somewhere a logic is based on the values of that enum is buggy
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/Profiling.Profiler.BeginSample.html
The Profiler API BegineSample has first parameter name of string type and the explanation for this parameter given in the docs is:
name A string to identify the sample in the Profiler window.
Can anyone tell me the real use of this name ? as in Is this name something that can be searched in the Profiler window: when using Hierarchy view not Timeline view(which is default)
It is searchable, nvm. I can search with that string. My code ran at zeroth frame which is not recorded. Was able to search that name in the profiler window on the next calls.
Hello. In a WebGL build, I have an update loop checking for when the player hits the ESC key. If the unity player has locked and hidden the cursor, hitting escape will NOT trigger the code to execute in the update loop, even though it does in the editor and desktop.
What is the best way to handle this? I simply want to achieve a situation where if the player is in first-person-mode with a locked and hidden cursor and they hit ESC, they will get their cursor back and stop causing player rotation. This seems like it should be easy, but I think some under-the-hood stuff with webgl is making it more difficult.
ALSO, i try detecting ESC with javascript, and if the cursor is locked, it doesnt detect it either....
What is the best, cleanest way to accomplish this?
I am trying to make a simple game where basically I need two textures to be compared and output a matching percentage of the first one to the second one. I experimented with for loops that do GetPixel in every pixel (Texture2D) but with no result. Also the textures are black shapes with white background, so if both pixels in x, y (first texture) and x, y (second texture) are black or both are white, int correctPixels++;
no need to cross post
@worn flower are you saying that https://docs.unity3d.com/ScriptReference/Cursor-lockState.html isn't correct? specifically when the user appears to exit full screen and the cursor is definitely not locked?
if so you should probably file a bug
Hey, I am trying to call a JS function from a c# class for my WebGL project, the only isssue is, that it does not build for some reason. Any idea how i can call the JS functions from within C#
the use of extern ```cs
[DllImport("__Internal")]
public static extern int WebSocketConnect(int instanceId);
that c# extern will point to a jslib file running within the same project that points to the function ```js
WebSocketConnect: function(instanceId) {
the naming of the method is important as it uses that to find the method in the jslib
thank you
Looking for a way to render an object under everything else, always, without using an extra camera.
I have tried setting a Sorting Group on the object with the MeshRenderer, but this isn't working
do you mean that when the object is closer, everything that is farther still gets rendered on top?
Yes, exactly.
This is my dumb advice because I know next to nothing about tricky rendering stuff, but I would try adding a shader to the obj with the "Queue" subshader tag set to "Background". I figure posting a probably wrong answer might at least provoke others to provide better advice
DIdn't work... 😦
Hello! I'm trying to make a login system so I have a singleton that contains the authentication session data and i'm assigning it values if the request goes well (login or register). I'm having an issue when trying to assign a teacher to it and it says something is null. I've debuged everything and the teacher i'm trying to insert is not null actually but maybe something's wrong with my singleton class, and btw Teacher class isn't a monobehaviour. Can you help me figure out what's wrong?
Clearly AuthSession.Instance is null
This is a #💻┃code-beginner question
oof ... after so many years on unity what a newbie 😖
Thanks and sorry
so I got this... (same objection positions, just a different angle proving white box is actually behind) it doesn't quite work if I leave the camera's skybox enabled in game though
I am going to try messing with it a bit
I just made a copy of a Standard Surface shader and replaced the tags and turned ZWrite Off (sorry should have mentioned that before) ```
Tags { "RenderType"="Opaque" "Queue" = "Background" }
ZWrite Off
nice!
I think it will lead to some pretty confusing perspective while moving the camera around lol
Basically I have an "outside" of a building, that is visible from certain places in the game, but when it intersects with the internal parts I want it to not render
makes sense
Hello! I have read some articles on switching between 1st and 3rd person cameras so I understand basics. However, I do not understand how to make functional in multiplayer. Take a game like CoD, you play in first person animations but see others in third person animations. How is this achieved? Please direct me to some resources. Thanks!
you simply render others as 3rd person, ignoring their 1st/3rd person state
Remote users send their current state. As for what they're doing.
Reloading/shooting/standing/crouching/running etc.
Whatever state their device sends, your device will try to play that state. Thats how multi player works in low level. Its not even related to first person/third person
Quick question: ScriptableObject data does not persist after a restart of the application right?
Depends can you elaborate?
Are you referenccing a scriptable object and editing the values at runtime via code?
if its a player (build), then no data can persist after an applications restart unless its a PlayerPref, which is stored elsewhere in hard drive
That is what I was searching for, thanks
anyone know anything about unity & spine?
Depends what you need to know
so we use spine & unity for the game were making and im trying to implement a backpedal but when i try to backpedal it interrupts the attack if you do it too early then you get stuck
in a backpedal state
That doesn't sound like an animation problem but rather a implementation problem on your code side
can you share the code aswell? looks like a problem in your end. i dont have experience with spine, but other people here could help you out with it
could very well be
this is my first time using spine ive used unity in the past but not in something as complicated as this
That's a lot of code, you should really isolate the problematic parts
Exactly, not everyone here have the time to read all those 800+ lines 😮💨
private void Move()
{
movementX = Input.GetAxisRaw("Horizontal");
movementZ = Input.GetAxisRaw("Vertical");
if (movementX != 0)
{
this.rb.constraints = RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionY;
//Start Moving
if (isWalking == false && isbackpedaling == false)
{
SetCharacterState("Running");
}
else if (isbackpedaling == false)
{
SetCharacterState("Walking");
}
else
{
SetCharacterState("Backpedal");
}
//Decide Direction
if (movementX > 0)
{
if (UnitForward == false && isWalking && isRecovering == false && attacking == false)
{
isbackpedaling = true;
}
else
{
UnitForward = true;
}
}
else if (movementX < 0)
{
if (UnitForward == true && isWalking && isRecovering == false && attacking == false)
{
isbackpedaling = true;
}
else
{
UnitForward = false;
}
}
}
else if (movementZ > 0)
{
//Start Moving Z
SetCharacterState("AwayStep");
}
else if (movementZ < 0)
{
//Start Moving Z
SetCharacterState("TowardsStep");
}
else
{
//Idle
SetCharacterState("Idle");
movementX = 0;
movementZ = 0;
}
}
thats movement code
thanks
the only problem is attacking is really long as well
is this code generated out of curiosity?
generated no its typed out
thats all primary action code
and finnaly ```cs
private IEnumerator WalkWait()
{
yield return new WaitForSeconds(1.75f);
if (movementX != 0 || movementZ != 0)
{
speed = normalSpeed;
walkTrack = skeletonAnimation.AnimationState.SetAnimation(0, run, true);
canAttack = true;
isbackpedaling = false;
attack1Fired = false;
attack2Fired = false;
attack3Fired = false;
}
else
{
speed = normalSpeed;
canAttack = true;
isbackpedaling = false;
attack1Fired = false;
attack2Fired = false;
attack3Fired = false;
attacking = false;
}
}
I need to wrap my mind around this, can you walk me through the animations you see, starting with attacking and then early backpedaling?
the main problem is just getting stuck if i swing my sword and during that time i attempt to move before the attack recovery has completed i either get stuck walking forever or i get stuck backpadaling forever its like if the attack is interuppted variable i have set in walk wait dont trigger
your code looks like they could use some refactoring, but lets put that aside...
if your walk wait doesnt get triggered, then most likely the attack animation is interrupted (the animation is changed before it's completed)
maybe you should disable moving while attacking animation is not completed
the problem with that is you need to be able to attack and walk at the same time
I'm not sure if spine animation support animation blending... or do you have attack while moving animation?
we have 2 different attacks 1 while idle and one while moving called attack1blend and so on
do you have attack while backpedalling?
if not maybe you can just disable attack while backpedalling
would it help if i just redid everything?
im sure theres a better way to dop what im doing
OK, I cannot seem to find an answer here, but I think this is the source of an issue I'm having: When you get transform.GetSiblingIndex are inactive objects counted in that index?
yes
Hi! i'm using UnityEvents for a few things, and i might not be understanding a few things:
public class CustomSCOLEvents : UnityEngine.Events.UnityEvent<CallEventAction> {
}
[CreateAssetMenu(fileName = "New Custom Action",menuName = "SCOL/Actions/Custom Action")]
public class CallEventAction : ActionBase {
public CustomSCOLEvents EventsToTrigger;
public async override Task Execute() {
EventsToTrigger.Invoke(this);
await Task.Delay(0);
}[...]```
Here, i'm passing my CallEventAction as argument, but how can i retrieve it in the called function in the event? IE: i'm putting this function inside the unity field:
which is basically ```cs
public void PrepareNikkyImpDialog() {[...]}
What can i do to retrieve my callEventAction in this? Do i need to add it as a parameter?
where are you passing the parameter?
in the "this", in the invoke
if you pay close attention, the parameter in my generic type is actually the class just below
what i meant to ask is, the object is being passed to UnityEvent<T>. but UnityEvent<T> is calling a UnityEvent.
the parameter is being discarded
there's no direct approach for something like this.
a custom inspector might work im not very sure.
but what you could do is, store the generic T instance somewhere publicly accessible.
store the object when you call the Invoke. Then consume it within the function
i don't think i've been clear of what i'm doing lol
Let me do a quick paint drawing
my assumption is that you want to access CallEventAction which you're passing via Invoke(this) in the function PrepareNikkyImpDialog()
am i right?
here;
so i don't need to actually see anything in the inspector
anything get passed down in the code (theorically)
basically, yeah...?
So you're saying that maybe i need to pass it down another way..?
I clearly can't do that, cuz the soul purpose if this CallEventAction scriptable is to being able to call it anywhere. I'll do what i need another way if it's not possible
public void PrepareNikkyImpDialog(CallEventAction action)
Then properly select it from the Dynamic section of the functions list
well yeah, i could do this, but thing is i've got other funcs like PrepareNikkyImpDialog where i already have an arg
so i can't pass down two bc of how unity events work
You cannot get the value unless you use a function that can receive it.
okok! got it
I really do not get what is the purpose of using a unityEvent with this generic type polymorphism thing
yes this is what I was trying to say basically
What's the purpose? To be able to serialize a simple function in the inspector. A perfect example is an InputField having a Submit(string)
I would love if they could support some more complex stuff, but it doesn't have that capacity
there are other simple options too.
passing true/false to GameObject.SetActive
well, if i bind a function that is defined as "SetActive(bool active)" in my script, i can do it with a UnityEvent without having it to be a generic type i created, right?
it will only need to serialize the boolean value. so yes no generics needed
okok! might be a 90° degree turn, but i basically wanted to do this so that if my event called an async Task, i could wait for it to be over with a workaround, and setting a boolean to my callEventAction saying it's over, yaddah yaddah... Anyways, i can't call a function that's not a coroutine by name, can i?
(unless i do like "switch(functionName)...." and hardcode all the names ofc)
i like to live on the edge 
So, I'm trying to lerp my slider to the target value when pressing the space key
https://paste.ofcode.org/4MWPwGQMZhe99Qda6LKdvV
But, it's showing
Assets\LerpSlider.cs(27,25): error CS0161: 'LerpSlider.LerpHealth()': not all code paths return a value
this is not really advanced, you only need to yield for IEnumerator functions
you can use Invoke([function name], 0) if you like
still aint workin, i've set the default slider value to 0, but it aint reaching the targetvalue 10, aand i ain't seeing any error like before
No you yield in the while.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
Go and read the docs.
The point of a coroutine is creating a routine which includes suspending an action until a certain condition is met, like waiting until a second passed. I don't see any form of condition in here
Your code is valid, but it will execute your while loop immediatley because it is not yielding based on some condition in there. I assume your program will lock up based on what the loop waits on
These type of questions belong in #💻┃code-beginner
Hello, does anyone know how is it possible to trim mp4 files with unity?
can i have arguments to my function...?
oh this is such a bad idea
what are you trying to achieve?
XY problem
Basically, ideally, i'd want my event invocation to have a workaround for asynchronous behavior. So basically imagine this:
public class CallEventAction : ActionBase {
public CustomSCOLEvents EventsToTrigger;
[HideInInspector] public bool finished;
public async override Task Execute() {
EventsToTrigger.Invoke(this);
await TaskUtils.WaitUntil(() => finished);
}
}```
And maybe what i could do is in each of my functions (that are all gouped in one scriptable object), i could have a custom implementation like so:
```cs
public async void Fun() {
CallEventAction action;
await Task.Delay(2000); //Do async stuff
action.finished = true;
}```
So i attempted having a UnityEvent with generic type (which does not help at all and actually does something that has nothing to do with what i want),
yeah, sorry, this is my problem :)
what is the purpose of the await after the event invoke?
Doesn't seem like the waiting in the first bit does anything? It waits then does nothing. So why wait?
oh, yeah my bad. Let me track the stack call for you, but we might unzoom too much:
Do you want to fire an event synchronously, and then start some async logic elsewhere based on that event? Or do you want to call an event from an asynchronous functoin and.. do what exactly?
Basically: my state machine is made of Trees. These trees, of leaves, and those leaves of actions. Polymorphic actions that can basically have anything inside them:
public async Task PlayLeaf() {
foreach (ActionBase action in actions) {
await action.Execute();
}
if (CharacterSystem.Instance.ClearCharactersOnEndLeaf) await CharacterSystem.Instance.CharactersAllGoAway();
}```
So the Execute is awaited here, and the PlayLeaf itself is awaited in the Tree.ResumeTree, etc etc.
you want to await the result of events?
don't do that, that's a bad idea
events are meant to be fire and forget
you're better off keeping a list of listeners then
oh
And triggering them by index or something? hmm
I'm trying to extend the Button class. I'll need very little functionality but I'm failing to figure out how I can run a method at the start of a scene. As it's not mono I don't have any access to start/awake. Is this not possible?
public class ToolButton : Button
{
private void Awake()
{
}
}
this is basically what I need tbh
Why ar eyou trying to extend the Button class? What are you trying to accomplish?
Button is a MonoBehaviour BTW, so Awake, Start etc will work fine
I did follow its inheritance but didn't see monobehaviour on any layer.
I'll have a few tools around and I don't wish to connect their identical onclick events. It was either this or a companion component to a regular button.
I'd go with companion and [RequireComponent]
oh i'm extending the wrong button...
Button -> Selectable -> UIBehaviour -> MonoBehaviour
But there's no reason to extend Button usually
May I ask what's the benefit of a companion over an extended class?
generally if you can choose between composition and inheritance, pick composition
mkay, tyvm
If you end up having some other piece of logic that would also need to be attached to a button, with composition you can just add two extra components. With inheritance, you're stuck
that makes sense
it seems like you're trying to make a rigidbody character. maybe try kinematic character controller from the asset store
you want to use a separate script for your animations. this script should make measurements / observe the rigidbody and other state and write those to an animation controller.
you also want to use Input System instead of Input
@dense echo so in my opinion you should rewrite what you have from scratch. authoring a state machine in an update loop ("updateloopese") isn't viable
you should use a second camera
you will need to do compositing of some kind in general, so it's unavoidable
i am looking at this online and it's just the cost of doing the effect.
this looks nice. did you build this?
you have some options you can try to explore.
i) use an extra camera with culling layer setup. this is the worst option because having multiple camera will just multiply the cpu overhead that many times. even more in HDRP which does not support camera stacking at all.(you can still get it to work, or use compositor, but you'll face unwanted issues later)
ii) use a custom shader to draw the object at the right spot. you can also use the render queue to control things in a similar pass.
iii) if you're using urp/hdrp youre in luck. you can use render objects (urp) and custom pass (hdrp) to do layer based sorting and draw objects in a specific layer in a different way.
In simpler words:
- writing a custom shader is the best option since thats per object. No need to waste a layer for this solution.
- render object and custom pass work on layer basis and only on urp and hdrp respectively.
- camera also works on layer basis but has extra cpu overhead and wont even work in hdrp.
hey guys, SO saves between scenes right? it only reset when u turn on/off game?
built version ofc
SOs are completely independent of scenes, yes.
Note that they don't reset in the editor, only in builds.
In the editor if you make a change to a serialized SO variable it will change permanently
yup, thank you 🙂
can anyone tell me why calling LobbyService.Instance.QuickJoinAsync is causing me to get an error when i pass it in as a parameter in the second line, but works just fine if i await it using the method in the first line?
it throws this error
and from what i've seen before, its usually because i've called a unity-function that's only meant to be called on the main thread. but these are async functions so it should be fine
Hey yall,
Any idea why OnDeselect() is not showing results? I'm using the IDeselectHandler properly with the using UnityEngine.EventSystems;
as well. The gameobject that holds teh script is a button which I want to be disabled when deselected.
using UnityEngine;
using UnityEngine.EventSystems;
public class EquipButton : MonoBehaviour,IDeselectHandler
{
// On equip button click event
public void OnClick()
{
// blah blah blah
...
// Disappear when tapped as well
gameObject.SetActive(false);
}
public void OnDeselect(BaseEventData eventData)
{
gameObject.SetActive(false);
}
}
[Solved]
is there an asset for extruding shapes / graphics? for example an svg, especially one that came in via unity's vector graphics package
New to C#
Trying to make this language more bearable. I see that it has support for destructuring.
No idea why a lot of the Unity structs don't support it out the box. Can anyone explain why?
I also found this extension: https://github.com/baba-s/UniDeconstruction
I tried to install it via the package manager but it doesn't seem to do much. Anyone have any ideas here?
that's it, that's how you do it
i don't think you want to deselect the game object #archived-code-general
did you write async task yourself? use unitask
don't try to do that stuff yourself, you did it wrong
You get an auth. error, so most likely the issue is not really in that code. How are you creating the thread this all runs in?
i just did a test to make sure that the player is in fact sign in before quick joining and im not getting a 404 code instead of 401 @compact ingot
seems like i can just ignore the 404 code though
Are you sure you are passing the required auth. info in your request? Bearer token etc.
@compact ingot im not sure where that would be shown. im initializing the unity services and authentication services within Start and then using their way of setting up the rest of the identification
Log the auth. state directly before making the request and ensure that your user has the permissions to access the api
what is your goal?
wrong person 😉
just trying to get unity lobby+relay+utp stuff working but every step of the way im getting problems
step 1 would be to get UniTask and ditch your DIY solution to make sure there aren't any bugs created by a buggy async implementation/wrapper/utility-thingmajig
step 2 would be to understand how the remote API works to avoid the permissions/auth issues
step 3 would be to build a utility framework around what you learned
the errors you have shown so far can only be solved by understanding how the lobby API works, if you post an exception that says "Failed to find any open lobbies" what kind of help do you expect to get here?
the errors you have shown so far can only be solved by understanding how the lobby API works
yea. the thing is that theres so much sample code to sift through and half of it is irrelevant. its hard to create framework when i dont know whats important.
ive been dealing with looking through Unity game lobby example project since friday, trying to pick through it and create my own code based on what they do
Hi guys I need your advice. I am self taught developer. I finished MIT CS106a and a couple of C# courses. I can do a lot of things in Unity. But it seems I have little knowledge about data storage and data structures ,graphs , lists , dictionaries, their pros and cons . Could you please recommend a book or online course for the subject. Thank you
@compact ingot also i dont really have time to sift through whatever UniTask is to figure out how that works too
Eh kinda comes down to just studying/using them really. I'd reluctantly recommend LeetCode for learning data structures. Most people will oppose this idea and I can definitely understand why, but I've learned a ton about recognizing which DS I need to use and why (as well as being able to factor in time complexity into the 'why').
Database stuff is a bit separate and more in depth depending on what you already know, or don't know.
Thank you Nutty I will give LeetCode a go. I usually use lists, arrays and dictionaries. But sometimes I feel like I am doing a wrong thing.
what is your goal?
create a networked multiplayer game? what kind of game is it?
its a golf game
@undone coral the object syncage should be super simple so i dont really need the Networked Game Objects package, i can handle syncing that stuff on my own, hopefully
making code for sticking people into a lobby was simple enough. coding the relay part is where i had to mostly rely on unity's RelayUtpSetup to get that all working because there's so much behind-the-scenes code that would take me forever to research
If you're intending to be a computer scientist then you really need to take a data structures course (and probably also algorithms) so you understand how they work under the hood and how to design and build your own. If you're intending to be a programmer, then you likely can get by just fine by continuously learning how to use new data structures that exist in .NET generic collections - dictionary, queue, stack, list, hashset: they'll do it better than you can, and they're far easier to implement.
When I say "computer scientist" and "programmer", by the way, I consider a programmer to be someone who generally consumes the API of other people, and computer scientist someone who has spent many years (either in school or not) studying "pure" computer science and math topics. 90%+ of programmers are "programmers" and not "computer scientists", I think.
In general, it's hard to study generic concepts without a background/degree in computer science, so your best bet for learning is to try to implement something yourself, and read as much as you can to learn the concepts for that task. Databases, networking, serialization, etc.
You'll probably also want to add "patterns" to your list of things to learn - which are also a little bit hard to study in the abstract, but still critically important to get good at if you want your codebases to be manageable.
I consider a programmer to be someone who generally consumes the API of other people
i think Unity's Gaming Service API gave me API poisoning, i dont feel so good
Edit: I do think I'm making some progress though
How can i Change the Alpha Channel from a Gradient variable.
I am using Slider component to fill the image with different values I am creating a healthbar but I want to decrease the alpha channel at some point and I can't seem to solving this :/ I saw like GradientAlphaKey something like that but didn't work and I wanna access it from other script
Thank you. Yep totally agree. I went through Computer Science course and it was very helpful. It now much easier to pick up different language. But I will need to learn some theory as well. Just so I know what to use and in which situations. Also practice
So I'm assuming you've seen this in the docs, but did you remember to call SetKeys?
I did yeah I could reduce the alpha but then I had problem with the color it changed. I am using slider with gradient so depending the sliders value change the color of gradient
But the color was changing
I assume I had a mistake on GradientColorKey but don't know how to get this done with the slider
i havent fiddled with those so im not too sure
To be honest I didn't try to use them both :/ don't know if that would have worked
What do you mean? You never used both gradient and slider? Plus alpha channel?
Yeah okay no problem thanks for trying ❤️
oh, i just use the one in the inspector. never really needed to programmatically change them before.
like for line renderers
Ohh it's okay :/ thank you very much 😊
The real stuff is MIT 6.006
https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/
and Introduction to Algorithms
https://www.amazon.com/Introduction-Algorithms-fourth-Thomas-Cormen/dp/026204630X/
Hey! I am trying to do a small little editor script that gets a prefab in the assets folder, creates a new variant out of it, and then duplicates the material inside if it has a mesh renderer, then finally assign them those materials. Sadly I cant get that last part to work, if I use .material the editor will error out saying I should use sharedMaterials, but using sharedMaterials doesnt assign the material, so i am a bit stuck
public void Duplicate() {
var targetPath = path.Replace(split, addedText + split);
//Instantiate Copy in Scene
var newObj = (GameObject)PrefabUtility.InstantiatePrefab(obj);
var meshRenderer = newObj.GetComponent<Renderer>();
List<Material> mats = new List<Material>();
if (meshRenderer != null) {
int index = 0;
foreach (var material in meshRenderer.sharedMaterials) {
string matPath = AssetDatabase.GetAssetPath(material);
string matSplit = Path.GetExtension(matPath);
string matTargetPath = matPath.Replace(matSplit, addedText + matSplit);
Debug.Log(matPath);
Debug.Log(matSplit);
Debug.Log(matTargetPath);
AssetDatabase.CopyAsset(matPath, matTargetPath);
mats.Add((Material)AssetDatabase.LoadAssetAtPath(matTargetPath, typeof(Material)) );
index += 1;
}
//replace mats in prefab
index = 0;
foreach (var material in mats)
{
newObj.GetComponent<MeshRenderer>().sharedMaterials[index] = material;
Debug.Log(newObj.GetComponent<MeshRenderer>().sharedMaterials[index].name);
index += 1;
}
}
//Save!
var variantRoot = PrefabUtility.SaveAsPrefabAsset(newObj, targetPath);
//DestroyImmediate(newObj);
}
this is the code
it gets the prefab (works), instantiates it on the scene (works), gets all the materials inside the mesh renderer(works), creates copies of these materials (works), then reassigns these copies to the scene instance (DOESNT work), and then saves the newly edited prefab (works!)
this is my issue and I cant find a solution
//replace mats in prefab
index = 0;
foreach (var material in mats)
{
newObj.GetComponent<MeshRenderer>().sharedMaterials[index] = material; //<- this doesnt nothing
//newObj.GetComponent<MeshRenderer>().materials[index] = material; //<- this errors out in editor
Debug.Log(newObj.GetComponent<MeshRenderer>().sharedMaterials[index].name);
index += 1;
}
any help would be appreciated
that would explain a lot
gimme a sec to try
Note that like all arrays returned by Unity, this returns a copy of materials array. If you want to change some materials in it, get the value, change an entry and set materials back.
this is a really backwards way to explain what you just said lol
works perfectly
thankssss
I was stuck here for half an hour haha
okay
i've engineered a golf game, and also directed a different golf game
one async multiplayer and one realtime
this is going to sound stupid, but why are you writing so much of this stuff from scratch
why aren't you using photon?
the guy assigning the tasks was wanting to use Unity Gaming Services
im not a fan of writing all this stuff from scratch
im used to using UNet where most of this stuff was handled automatically
does it have a lobby system and does it have a way to have a server that runs the game logic instead of a player hosting?
oh it looks like they do. maybe i can convince them to use that instead
@undone coral lmao one of the guys on the team saw this and said "Nice ad, it's telling us something"
lol
golf is the perfect game for photon's networking model
as long as you don't need the balls to collide with each other, which none of these games do
that was potentially going to be one of the things that they do 😬
i'd rather they not, though
the chance of players having their balls collide when launching them at the same time is gonna be rare im sure
balls colliding when they're rolling on the ground would be more likely to happen
Many golf games allow ball collisions but they're relatively rare and they're expected to be chaotic anyway so it works fine.
😄
switching over to Photon immediately to try it out 😄
although "Photon" doesn't mean much - they have at least 3 networking products:
- Pun
- Bolt
- Fusion
Which kind of network model or package is best? Thinking of multiplayer, did some research but showed up with many options
The best is the one you like that suits the needs of your game
I have a class whose majority of its methods take in a string, and converts it to its class counterpart. More specifically, I am working on a visual novel characters script, and the methods take in a character name in string, and gets the actual character class from a dictionary. Many of these methods accesses the dictionary for the character class. Is there a way to abstract the accessing of the dictionary? Sort of like decorators in python
use an enum
an enum is basically a finite set of distinct values. you can access the dictionary using the enum values as a key, which means you basically make it impossible to supply an incorrect argument
As in, replace the string in the parameter of the methods with an enum?
public class Character : Monobehaviour
{
public enum Name
{
Rick,
Stan,
Beth
}
private Dictionary<Name, Character> _prefabMap;
protected Name _name;
public Name Name => _name;
public static Character Generate(Name characterName)
{
var result = Instantiate(_prefabMap[characterName]);
return result;
}
}
something like that
you have a public factory method that takes in a "name" argument, instantiates the prefab, and returns the reference to the calling code
Oh I see. So in the methods that take in that enum, I call the Generate method to get back to Character class?
Or do I call the factory method before passing into the method?
yeah so the calling code would look like
public void GimmeRick()
{
var rickInstance = Character.Generate(Character.Name.Rick);
rickInstance.DoRickThings();
}
it's just a standard factory pattern naming
Ah, that's what I thought, interesting, I didn't know that, thanks for the help
you could do Create, Spawn, whatever you want
np! I hope that's along the lines of what you're looking for
a tag-along pattern that might be useful is to create a "palette" of prefabs as a scriptable object, so you can build the dictionary automatically
What is a tag-along pattern?
like you could make a script that extends from character like this:
public class Rick : Character
{
// Rick comes packed with his own name so we can build the dictionary with no extra data
_name = Name.Rick;
}
[CreateAssetMenu(menuName = "CharacterPalette")]
public class CharacterPalette : ScriptableObject
{
[SerializeField] private Character[] _prefabs;
public Dictionary<Character.Name, Character> CreatePrefabMap()
{
Dictionary<Character.Name, Character> result = new();
foreach (Character prefab in _prefabs)
{
result[prefab.Name] = prefab;
}
return result;
}
}
assuming the parent class has a protected _name variable and a public property Name to access it
yadda yadda
That's super cool, thanks for the insight
I have been trying to fix my weapon script. Currently it holds everything that any type of weapon needs but I have some weapons where a lot of the variables are redundant (Ranged/melee or requires ammo/Doesn't require ammo). How would I go about fixing this for different weapons?
don't have one script that does everything
have an abstract weapon script that has all the attributes and definitions all weapons will need, then make other scripts that extend from them and specialize
@undone coral can Photon Fusion handle lobbies by itself or do i have to use PUN 2 also?
I usually do this when not on unity...
But for unity I usually go with component based, instead of abstracting all attributes, I divide them into corresponding component...
like
-bullet component (damage, velocity)
-propeller component (acceleration, maxVelocity)
-homing component(target)
that's fair. it i wanted to do it compositionally, i would probably have like socketed sub-components, if that makes sense. like have interfaces defining how a component can interact with a base weapon
like IOnBulletHit, IAmmoConstraint, IFireRate
and then i can predefine a suite of subcomponents and build weapons compositionally, like the base weapon knows how to consume all the subcomponent interfaces and ALL the weapon does is apply them
and then you can build weapon configurations as scriptable objects, so you can literally slap them in completely modularly
(though interfaces don't work for that, which sucks, so i'll probably use abstract base classes as a pseudo interface even though it's gross
I SO WANT to be able to serialize interfaces in unity
[CreateAssetMenu(menuName = "WeaponConfiguration")]
public class WeaponConfiguration : ScriptableObject
{
[field: SerializeField] public IOnBulletHit OnBulletHit {get; set;}
[field: SerializeField] public IAmmoConstraint AmmoConstraint {get; set;}
[field: SerializeField] public IFireRate FireRate {get; set;}
[field: SerializeField] public IBurstRate BurstRate {get; set;}
}
that would be SO SEXY
but abstract classes are just as good, just a little more constricted
Stropheum getting turned on by code... nothing to see here
I dont like abstract classes, feels like I'm writing something that I will never use
you're writing a contract
Then you're using them wrong
not particularly abstraction, but maybe the whole oop concept I don't like...
dont get me wrong, I was using c++ with irrlicht, and flash/as3 before, and I have no problem with oop, but comparing to how unity implemented component based it feels like it's more effective (although it's most likely biased/not apple to apple since unity is a complete game engine).
if you don't like OOP then you might want to rethink games lol
the few forays into like pure functional programming are exclusively meme passion projects
oh i see what you're saying, like entity/component models are still OOP though
🤔 maybe I should say inheritance...
well using inheritance in this sense is just to group the types of compositional pieces
like "these are things you can cram into the ammo slot"
"these are the ways you can manipulate fire rate"
it's like how a motherboard has sockets for ram and graphics cards and cpu's
you have a collection of compatible cpu's, a collection of compatible RAM, a colletion of compatible GPU's
you know like
creatures -> biped->humanoid->elf
most likely I ended up with 'useless' classes like creatures and biped
which contains nothing but abstractions
they're only useless if
-> you don't define abstract behavior
-> you don't utilize the abstraction as a contract
like
Also no one is saying that you should start that low level
sec i'll show you something interesting
public abstract class Mammal<T> : MonoBehaviour where T : Mammal<T>
{
public abstract void HaveSex(T other);
}
public class Breeder<T> : MonoBehaviour where T : Mammal<T>
{
[SerializeField] private List<Tuple<T, T>> _animals = new();
public void AttemptBreeding()
{
foreach (Tuple<T, T> pair in _animals)
{
pair.Item1.HaveSex(pair.Item2);
}
}
}
i think this is called a fix-up pattern, but basically this is a structure where a type is templated to pair while child types of the same type
so a kangaroo which derives from mammal will only be able to HaveSex with another kangaroo
but that functionality is abstacted
which allows you to have a generic breeder class that can store collections of mammals, but the contract of the Mammal<T> class can store ANY mammal, but only one kind of mammal per instance
calling code could be
public class Farm : Monobehaviour
{
[SerializeField] private Breeder<Cow> _cowBreeder;
[SerializeField] private Breeder<Sheep> _sheepBreeder;
private void UpdateBreeders()
{
_cowBreeder.AttemptBreeding();
_sheepBreeder.AttemptBreeding();
}
}
that's something incredibly powerful that you can't get strictly from compositional design
i only did the list of tuples to demonstrate that the generic type can also use type enforcement which is poggers as hell that you can do in the base class
🤔 interesting indeed...
using compositional, I can see that it cant be written that short... need to divide/define the breeding components first, then, well... it could be a long story
using composition you'd have to define the same method uniquely for every component, and then have some other heuristic for determining how components can interact or where they belong
also the fixup pattern has this little weird syntax, because you have to template the child classes to themselves
public class Cow : Mammal<Cow>
{
public override void HaveSex(Cow other)
{
//yoink the udders or something idk
}
}
public class Sheep : Mammal<Sheep>
{
public override void HaveSex(Sheep other)
{
// baaaaaaaah
}
}
but that's how you enforce the type interaction
OH
i learned a thing
this is called CRTP (curiously recurring template pattern)
Lmfao I just wanted to take a look at the channel and the first thing I see is "COW SEX, SHEEP SEX, BAAAAAAH" LOL
Thank you! I will probably go for it as I already done CS106a and it was amazing
Hi guys, can someone help me porting this JS code to C# ?
var XYIterator = function(width, height) {
this.width = width;
this.height = height;
this.x = -1;
this.y = 0;
}
XYIterator.prototype.next = function() {
if (this.y == this.height) {
return {
x: this.width - 1,
y: this.width - 1,
done: 1
};
}
this.x++;
if (this.x == this.width) {
this.x = 0;
this.y++;
}
if (this.y == this.height) {
return {
x: this.width - 1,
y: this.width - 1,
done: 1
};
}
return {
x: this.x,
y: this.y,
done: (this.y * this.width + this.x) / (this.width * this.height)
};
}```
No?
Replying to myself, probably something like this :
public class IteratorResults {
public int x;
public int y;
public int done;
}
public class XYIterator {
int width;
int height;
int x = -1;
int y = 0;
public void Init(int width, int height) {
this.width = width;
this.height = height;
}
public IteratorResults Next() {
IteratorResults result = new IteratorResults();
if (this.y == this.height) {
result.x = this.width - 1;
result.y = this.width - 1;
result.done = 1;
return result;
}
this.x++;
if (this.x == this.width) {
this.x = 0;
this.y++;
}
if (this.y == this.height) {
result.x = this.width - 1;
result.y = this.width - 1;
result.done = 1;
return result;
}
result.x = this.x;
result.y = this.y;
result.done = (this.y * this.width + this.x) / (this.width * this.height);
return result;
}
}```
have a look at IEnumerable and IEnumerator to do it the idiomatic way
https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator?view=netstandard-2.0
Oh, thanks 🙂
public void SelectTool(int index)
{
_selectedTool = index switch
{
0 => new LinkTool(),
1 => new UnlinkTool(),
_ => null
};
ToolChanged?.Invoke(index);
}
I'm trying to make a sort of in-game editor with multiple tools. This is my manager's method for changing the currently active tool. I was hoping to somehow serialize a type on my tool buttons, and pass that along the click event to my manager. Since if this goes on like this, I doubt it will be scalable.
How do people generally handle serializing of spawned objects? Taking care of persistent objects in the scene is fairly easy since they're already instantiated at load time, but spawned objects aren't as easily restored. Since all spawned objects come from prefabs in our case I'm thinking of putting the prefabs in the Resource folder & then serialize the prefab path, I can then instantiate these at load time & feed them the serialization data, but perhaps there's a different way to do it? Resource folder seems frowned upon overall by the documentation.
Maybe create a scriptable object to define your prefab data then make a spawner script that holds an array of scriptableobjects to pick and instantiate from.
You can even create this scriptableobject at runtime and serialize the spawner array to update it and store its content.
Hey, I am using HDRP and I am trying to blit my targetTexture (of my Camera) to the backbuffer (to the view), I tried using Graphics.Blit but it seems to not do anything, and I tried using CommandBuffer which I don't find a way to render to the backbuffer,, any idea what I should do?
Basically the BuiltinRenderTextureType doesn't contain anything related to the backbuffer except the GBuffers, but I want one end buffer to write to
graphics.blit and onrenderimage and other api's are not available in any SRP
you should use a custom render feature and custom render pass instead. https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@14.0/manual/Custom-Pass.html
@drifting galleon I'll check it out thanks
I don't think I understand async / await. I have a method that takes a long time that is currently running on the main thread, I want to make it so that it runs on another thread, and when it has finished running, returns its result on the main thread so it can be used. How do I do that?
with async / await
post your code
Hey guys I am having an issue with building once I added 'Amplitude' an analytics plugin for Unity
When I try to build from XCode
I get this
Anyone who is able to point me in the right direction I would be eternally grateful
Guys, is it the right way to mix two Color32[] ?
Color32[] CombineColors(Color32[] source, Color32[] colors) {
int numColors = source.Length;
if (numColors != colors.Length) return null;
Color32[] combinedColors = new Color32[numColors];
for (int i = 0; i < numColors; i++) {
Color sColor = source[i];
Color cColor = colors[i];
combinedColors[i] = sColor * cColor;
}
return combinedColors;
}```
You can use Color.Lerp instead.. Color.Lerp(somCol, otherCol, 0.5)...
But it still not the proper way of doing it, im on my phone, so cant really type that comfortably
Color final_color = Color.Lerp(someColor, otherColor, otherColor.a / 1.0f); better ?
Still incorrect, this what we called linear averaging... You'll get wrong color
Maybe this ?
float r1 = someColor.r;
float g1 = someColor.g;
float b1 = someColor.b;
float a1 = someColor.a;
float r2 = otherColor.r;
float g2 = otherColor.g;
float b2 = otherColor.b;
float a2 = otherColor.a;
float nr = (r1 + r2) / 2f;
float ng = (g1 + g2) / 2f;
float nb = (b1 + b2) / 2f;
float na = (a1 + a2) / 2f;
Color newColor = new Color(nr, ng, nb, na);```
Can be simplified but this is the idea
Am I using await correctly here? I want the main thread to keep running while waiting for a response from GetMatchListAsync
Your idea turns out to be not-so-great idea...not aure what your doing there 😀 .. if you divide it by 2 the color will be way much darker, just give it a try, you'll see... Google up how to combine colors, if you cant find it i'll answer it when i get back to my desk
That's what i've found googling it on the unity forum searching for not linear averaging method ^^
i don't think there's any color blending algorithm that perfectly mixes colors like they would irl
but ig you can get pretty close
There's a proper way, dividing by 2 just straight up wrong
Maybe this ? This should make the color less darker than dividing by 2
float nr = Mathf.Sqrt(r1 + r2);```
Am I using await correctly here?
no
is your objective to mix colors like mixing paint?
what's your bojective?
How should I use it then?
serializing for the purpose of saving a game?
start with "c# async await tutorial"
it's all documented online
you should see in your snippet you're not using the await keyword
you can also look into UniTask to avoid common pitfalls
with using async/await in unity
I'm trying to render multiple layers of nebulae
you probably wanted to start with an asset store asset for visual novels. dialogue system is a good one. otherwise look at Ink.
sounds cool
i'm not 100% sure why you need to mix colors for that though
in code i mean
why aren't your nebulae textures? can't you put them on quads and have them blend with alpha?
Yeah I think the way to blend your colors depends on what your inputs are and how you want to render it
If your colors are sRGB then you have to do an inverse gamma correction to convert it into linear mode and blend it there
Trying to port https://github.com/wwwtyro/procedural.js into Unity to generate a Texture2D then a sprite to make a background for a 2D game
can't you just save it as an image?
I think you can with SerializeReference
i can, but i always prefer having control over what i use so if i want to tweak things, i prefer porting it to C# (and into Unity) (sorry for my english...)
The team I am in had used a dialogue system from the asset store before, but wanted to make one in house. Anyway, it's basically done so it's too late for that.
And we use Twine for the writing
right, then have you tried your C# port yet? does it look right?
Can you? I need to try now
Yeah, it's in the Unity docs
It's a fairly new feature
not completely done yet but things are going well 🙂
public interface IFireRate
{
public float RoundsPerSecond { get; set; }
}
public class Gun : MonoBehaviour
{
[SerializeReference] private IFireRate _fireRate;
}
well this is a thing. I can serialize the NAME of the interface lol
That's strange. When I did it, I used Serialized Reference with a list of IClass, and it worked, and I was able to see each instance of IClass in the inspector.
which unity version
Try adding [Serializable] to the classes
maybe a concrete implementation needs to exist?
So in your case, Add [Serializable] to IFireRate
Wait a second
Yeah, you need a concrete class
There is no drawer for serialized references without a value
if it's null, you will not get a drawer unless you use a custom package
I mean, if you think about it, there is nothing to serialize if there is no information
https://github.com/vertxxyz/Vertx.Decorators here's my drawer
@calm ocean you said you were able to serialize the type of IClass
My bad, I meant classes that implement IClass
well that's just serializing 
You can serialize instances in a field declared with an interface just fine with serializereference.
yeah just not without a custom drawer. that's fine i spoze
literally all i want to do is just like
[SerializeReference] IFireRate _fireRate; and drag in a reference to a script that implements it
i feel like that should be out of the box
You cannot use UnityEngine.Object types with SerializeReference
i'm aware. that was my original complaint, and someone was just telling me otherwise so i got my hopes up lol
wait why tf is this example working but mine wasn't. from the unity docs
Because they initialised it with values
It just draws nothing but the label when null
oh that's interesting lol. so all i have to do is just, ok ic ic
public class Gun : MonoBehaviour
{
[SerializeReference] private IFireRate _fireRate = new DefaultFireRate();
}
public interface IFireRate
{
public float RoundsPerSecond { get; set; }
}
public class DefaultFireRate : IFireRate
{
[field: SerializeField] public float RoundsPerSecond { get; set; } = 1.0f;
}
so something like this then should work
ohhhhhhhh i see why you used the custom drawer. so you can select from the concrete types via some enum
seeing all of this makes me glad I bought odin
Can anyone test this and tell me what's wrong ? For testing, attach the script to a sprite renderer. This is my attempt to port this js project/app : https://github.com/wwwtyro/procedural.js
I've set width and height to 32 for testing purpose.
unity drawer code has way too much boilerplate
small stars are rendered well but not the other stuff
oh, you will need the Noise script for testing too
https://paste.myst.rs/3wfsf0yr slight hack i guess but this is a potential workaround
serialize an enum, construct a different concrete implementation based on the selection and expose the property as the interface
does odin do this out of the box?
i actually bought it but it's got so many features i haven't actually used it yet cause i wanna read up about it
oh it does, that's amazing. okay definitely using odin in everything now

