#archived-code-advanced
1 messages · Page 185 of 1
np, you cold also create a margin where if the distance is further then the minimum but still close to the ground, you can lerp between the ground point and the original point
but this all depents on what you use it for
yeah then you should use the aron granberg asset
and when using the raycast be carful when using it every frame
it's the only one with an RVO demo that works well that i'm aware of
Ok thx ^^
yea, was actually gonna ask if this holds up if I care about performance lol
didnt work
Raycasts are not as bad as most people think, but I would keep it under 50 - 100 per frame. For placing things one it's perfect and you can get away with lots
runs once then doesnt yield again
more than a minute goes by and nothing happens
delay is set to 0.1f as you can see in the Debug.Log
if (hits <= maxHits) sounds like Updateloopese. you should write a coroutine to describe the entire DOT effect, including each individual hit.
wdym, it should work this way, i am updating the hits, and if it doesnt hit it just breaks to prevent looping
its a coroutine that "yields itself" isnt that functionally the same?
i never StopCoroutine
i haven't seen the code, and you're telling me it doesn't work... so i guess you have to share the code 🙂
thought it would be enough from the SS, give me a minute
IEnumerator DOT(Vector3 landingPosition, float AoE,LayerMask monsterLayer, float damage, float clingDamage, float delay, float maxHits, bool doesCling, Collider[] clingColliders)
{
float hits = 0f;
Debug.Log("I have " + (maxHits - hits) + " left");
if (hits <= maxHits)
{
if (doesCling)
{
foreach (Collider col in clingColliders)
{
if (col.CompareTag(enemyTag))
{
Debug.Log("dealing "+ clingDamage+ " cling damage");
col.GetComponent<MonsterHealth>().TakeDamage(clingDamage);
}
}
}
Collider[] activeColliders = Physics.OverlapSphere(landingPosition, AoE, monsterLayer);
foreach (Collider col in activeColliders)
{
if (col.CompareTag(enemyTag))
{
Debug.Log("dealing " + damage + " active damage");
col.GetComponent<MonsterHealth>().TakeDamage(damage);
}
}
hits += 1;
Debug.Log("ending this cycle, yielding new one in " + delay);
yield return new WaitForSecondsRealtime(delay);
}
else
{
Debug.Log("breaking coro");
yield break;
}
}
there is no while loop
because it wasn't a coroutine
#archived-code-general you can learn more about coroutines
lets see if it freezes
you will need to master some C# concepts to really get this going 🙂
ive been using C# for like 5 years, im surprised ive never had to use while loops
dependency injection in Unity is very low ROI
i jsut used For and foreach instead of whiles until now
as far as i know, maya has a way to project a polygonal mesh onto the surface of another. that means blender probably has it too. you can try finding out what that tool is called, then look at the source for blender's version. i imagine it's pretty finnicky.
you should use git
you will need to set up git lfs
github's can be very expensive. there are ones that are one-click installable in an AWS account, so you only pay for usage
if all of this sounds too complicated, plastic is as good as not using source control - you might as well use Google Drive
Yes, I have been building Standalone windows builds for a while now. Or the windows platform on Unity Hub is different from this one? I couldn't find any windows playform on the Package Manager
Some strance ECS stuff I want to experiment with
Hi, is there a way to check if scene is a prefab's scene? I see that only name of the scene is equal to prefab's name.
?
When you open your prefab unity creates a virtual scene to edit this prefab. I try figure out when gameobject is in real scene and when it in virtual one
I'm guessing something in here will help: https://docs.unity3d.com/ScriptReference/SceneManagement.EditorSceneManager.html
Maybe the prefab isolation context is a Preview Scene? 🤷♂️
Windows Build support is somthing within the editor and not the Package Manager. You should make sure the modal is added in Unity Hub
@gray pulsar , You should be able to change the prefab preview style in the editor to see it in it's context
let me quickly open unity and show where it is
I think you meant to ping @austere summit, but also I think they want to do it via script, not just w/ a visual cue
You can change the context here
You can also see it when looking at this
And navigate to the scene
Yeah, within a context all goes well, but my script logic doesn't work well with prefab opened through project separately from any scene
I mean like this
Oh, so you wanna test your code within the prefab preview?
yep
For that scenario I would make a separate scene just for testing prefabs
i have custom sprite rendering system which works on DOTS and i'm trying to write in-editor rendering. When gameobject is in the scene or opened within a context all renders just fine, but there is a problem with prefab preview scene
mm, I would not know how to fix that. Maybe changing the settings in the preview scene helps, like enabling lighting etc.
Like enabling always refresh. skybox those things
Are scriptable objects instances, or templates?
When you write a scriptable object script, that's a class like any other C# class. When you create a scriptable object asset from one of your SO scripts, that asset is an instance of the SO class
Ok, so if 2 gameobjects have a reference to the same SO asset, they're referencing the same instance?
"one copy of the data in memory" ok that answers my question
where do I start with learning on-the-fly building generation?
like, I have 4 points and I can stretch them in the editor and have a building update itself
how do I start with learning how to code geometry like that
ok
Having searched everywhere on Google all day on this one question, I thought I'd check in here in case someone can help me figure this out.
Ok... Using Unity 2020.3.24f1, I'm trying to implement IAP. My project is Android but will maybe go iOS later if app is popular.
I have my "Subscription Product" set up on Google Play, and my app is able to successfully purchase that product, it appears to be renewing itself every 5 mins, since the app is in internal testing.
So....
How do I check if the subscription is active, every time I open my app?
I tried to implement some code in "OnInitialized()" within my IAPManager class, but that method is never called (It is attached to a GameObject).
Don't cross-post, see #854851968446365696 for code posting guidelines (a screenshot that zoomed out is unreadable)
...I realised my question is probably classed as advanced... Should I delete the one in #archived-code-general ?
Yep you can do that
If you don't know why your method is not being called, you should stay in #archived-code-general at best
@strange cradle your class isn't implementing anything
should probably be implementing IStoreListener
Start() is called when you Start the scene, so maybe put the code in there?
In the meantime I looked at your screenshot and your method doesn't execute because it isn't referenced by anything, if that was supposed to handle an event
Ah yes, that was one of the things I tried adding, however it seemed to require some methods, which read as thought they are going to conflict with the existing classes? I could recheck to be less vague on that?
interfaces tend to require methods, yes
ty brb
If there are some methods you don't want to provide implementations of, just make a stub, or keep the one VS auto-generates when you use the "Implement Interface" quick action:
public void InterfaceMethod() => throw new NotImplementedException();
Yes, I'm just looking at that now. Struggling with PurchaseProcessingResult, it expects to return something
Throwing an exception will remove the requirement to return a value
.....but, shouldn't I give it what it needs, to function correctly?
Ah, if you do want to implement that method then yeah, you have to return something
I was still on the "I don't need that one" part
It wants to return a "PurchaseProcessingResult" but I'm not sure how to get that
What type is PurchaseProcessingResult? Class, enum? The light theme has different colors compared to the dark one, so I can't determine the type by looking at the color of the type
enum
Yep, so you can just do return PurchaseProcessingResult.SomethingHere;
Where you replace SomethingHere by one of the supported enum values
return PurchaseProcessingResult.Complete;
vs
return PurchaseProcessingResult.Pending;
...I'm certain it's complete at this stage. Curious why it gives me the option for Pending
PurchaseProcessingResult Applications should only return PurchaseProcessingResult.Complete when a permanent record of the purchase has been made. If PurchaseProcessingResult.Pending is returned Unity IAP will continue to notify the app of the purchase on startup, also via ProcessPurchase.
Looking at the Docs for it it's to use when you make the purchase request asynchronously
Interesting... But, I'm thinking this stuff is handled for me?
Yeah, so it does indeed check periodically for purchases that are pending, for you to check whether it has completed
It just runs the method again and again for you to get an update from the server
Ok...
So I have added "IStoreListener" to my class.
I have implemented "PurchaseProcessingResult" and "OnInitializeFailed", as per requirement of the "IStoreListner".
However, My OnInitialized is still not being called.
Yes, my Start() is being called, but not OnInitialized.
It was suggested earlier that I should manually call it from my Start(), but I was unable to supply the controller and extensions parameters to it
Yeah I've never used that package, but seeing how most packages are made you may have to somehow register your class to something, so it knows that's the one to call methods on
Not sure though, check the documentation on how to do that, if you have to do that
Honestly.... All I need is the ability to buy a subscription, which I've got. and then to check if the current user has that subscription.
Other than that, I dont care how it's done, or what package I use for it.... Completely open minded....
How would you implement this check
I've looked through the docs, and I still cant figure it out.
I'm looking through it now, seems like you have to register the products, then call UnityPurchasing.Initialize()
I'd really like a method...
bool IsThisSubActive(String subComName)
....first this I see is that "MonoBehaviour" is not there?
Should I remove it from my class
Yeah that should not be attached to a GameObject
Oh? I should remove it from my GameObject?
...just leave the Cs in my Scripts Unity Folder?
Yep exactly
ok cool ty
Still looking through the docs to see if you have to create the class yourself or IAP discovers it automatically
After removing the cs from the gameobject, I see that my Start() isnt running, nor is the OnInitialized
"public class IAPManager : IStoreListener"
Yep that's normal, since that was MonoBehaviour the trigger for any Unity message to run, you'll need to put the code that initializes it all into a constructor
We're back into plain old classes
Forgive me... I'm not familiar with 'constructors'
It's special methods that are run when you create new instance of classes. They have no return type, and their name match the class name
class Sample {
public Sample() {
// a constructor
}
}
The code inside of it will run when you'll do new Sample()
It doesn't mention whether the fricking constructor is called automatically or if you have to do that yourself
I appreciate you continuing to help me.
However, I'm struggling to wrap my head around what I should do, to call this IAPMagager of mine.
So, I've removed the MonoBehaviour from it, and the cs file is just sat in my Scripts folder.
So... Do I need to make a seperate cs, with a constructor in there, and then have the IAPManager inside that? 😬
Yeah you could try that, basically in your IAPManager class you declare a constructor that will register products and initialize the IAP, like in the example
Then from another script, this time attached to a GameObject, in Awake or start you do new IAPManager() and see if any of the initialization methods get called
Running this, does not run my Start() or OnInitialized() (Inside the IAPManager) 😢
Post the contents of your constructor. Start on IAPManager won't run because it's a Unity method only available on MonoBehaviour. Track the execution of the constructor instead.
how would i make a ui prompt show up and the user be able to execute a script when showing that prompt
im guessing using raycasts?
What have you tried?
what?
Did you post in this channel because it was active
As here, #archived-code-advanced expects advanced questions, and research
um k?
I don't see a constructor here
Again, as this class does not derive from MonoBehaviour Start won't be called
I may have misunderstood how to wrap this in to a constructor
I was able to successfully get those methods to run, after doing the constructor correctly.
However, now my purchase button is no longer bringing up the Google Play's confirmation dialog, when running on the device.
In the Unity IDE, I do see the fake store confirmation dialog though 😢
Also, on the device, my text4 output is showing that my 1 product is listed, but with no receipt.
My next step was to click purchase, and I expected to see the google pop up, but nothing happens when pressing the button on the device 😢
are you using a Normal, Bog Standard Android Device?
or are you an android power user
It's a Galaxy Note8
I have....
However, I think I just managed to bypass the problem by 'not' using the IAP Button Component on my button
Calling Controller.InitiatePurchase manually, seems to work... But I'm not sure if that will translate over to the iOS (But thats not too important right now) just worried I'm doing it all wrong....
I feel like I've made a mess of my code to achieve this
I feel like I've made a mess of my code to achieve this
it does seem that way yeah
the workflow for IAP is
user taps buy button
-> completes purchase
on platform
-> platform gives you receipt,
which you interpret
cryptographically and
award user item
everything else is a failure case and you do nothing. you don't attempt to recover
i have a feeling you are trying to recover from failures
Yeah you cant recover from failures with those kind of atomic operations
it either goes through or it doesnt, there is no recovery process, you just reattempt the transaction again
it looks like part of it is you're using the platform to manage your inventory
i wouldn't do that. you just have the inventory in game. in the platform, you create corresponding price objects and you verify the user bought something of the right price, not a particular item
does that make sense?
finally, you have restore purchases
😬
I'm not sure lol
I only have 1 item, it is a subscription for 1gbp a month.
I just want to check if the subscription is active, and then I'll disable the ads
I wana thank everyone who's helped me... I think I'm at a good point now...
Hey everyone, so I got an EAN code scanner which starts a thread, but the problem is, I want to start a safe code part form this unsafe void. I get of course the error "StopAllCoroutines can only be called from the main thread." So how can I ensure, I call it on the mainthread or something?
You'll have to notify the main thread somehow
My favorite technique is to use a ConcurrentQueue
So enqeue in the mainthread?
Hm okay, I guess I gotta google around a bit 🙂 Thanks for pointing
you can use UniTask, and do something of the form
async UniTaskVoid Scan() {
await UniTask.SwitchToThreadPool(); // or a synch context
// of your choice
var image = EANCodeScanner.Scan(); // this can be a plain old blocking call
// but naturally if it is async use that
await UniTask.SwitchToMainThread(); // wow.
GetComponent<Image>.sprite = new Texture2D(image);
}
whaddya think?
too cute for my blood doc
lol
c'mon. // wow. that's a good one
something stirred in your hardened heart
It made me think of doge
yes
"no queue" "wow" "is async" "so short"
#1 go to #archived-code-advanced and ask question
#2 UniTask
you might have something of this form
sealed class EANScanner {
static void Scan(Action<Image> callback);
}
and callback is invoked on the EAN scanner thread. in which case:
async UniTaskVoid Scan() {
var scanResult = new UniTaskCompletionSource();
EANScanner.Scan((image) => scanResult.TrySetResult(image));
await UniTask.SwitchToMainThread();
var image = await scanResult;
GetComponent<Image>.sprite = new Texture2D(image);
}
I actually just found this 🙂 https://github.com/PimDeWitte/UnityMainThreadDispatcher Thanks a lot for your async idea too. Will think about that too 🙂
no dude. this is literally just ripped out of unitask
use unitask
oh look https://github.com/PimDeWitte/UnityMainThreadDispatcher/blob/24f396350c63fb2e65bc156a88acbaa7eb6cb88b/UnityMainThreadDispatcher.cs#L33 it's exactly my concurrent queue idea 😛
Or just one queue, because it's just one queue
curiously thogh
does uniTask let you enter the main thread at specific parts of the event loop
it does!
it takes a player loop argument
like I can jump in during FixedUpdate?
yeah
you can jump at any time
it has PreFixedUpdate, PostFixedUpdate, etc. etc.
I see
// wow
if there's a script you drop into all your projects to do that main thread scheduling via a concurrent queue, you can also just drop in UniTask with the same amount of effort
for my platform i force people to install unitask
that's how much i love it
i'm a unitask stan
has it changed your life in some way?
it helps me run heaven up here, where people ascend to
helps me schedule everything in one giant async task
Sounds more like hell
lol
it went well, 1 gameloop task
lemme pull it up
for a sneak peak
literally a game loop
while (Application.isPlaying)
{
// click a play button
await
(m_PlayNowButton.OnPointerClickAsObservable() ?? Observable.Empty(default(PointerEventData)))
.Take(1)
.ToUniTask(cancellationToken: token);
m_ScoreCurrentControl.Reset();
m_ScreenView.Transition(m_PlayingScreen.screenIndex);
// game loop began
// wait a beat
await UniTask.WaitForEndOfFrame();
m_ThrowControl.enableNextThrow = true;
m_ThrowControl.StartThrowingGame();
// wait until the next throw to start the timer
await m_ThrowsSubject
.Take(1)
.ToUniTask(cancellationToken: token);
// start the clock
var timeElapsed = new CancellationTokenSource();
var anyCancellation = CancellationTokenSource.CreateLinkedTokenSource(timeElapsed.Token, token);
var clock = UniTask.Create(async () =>
{
var startTime = Time.unscaledTime;
var didLowTime = false;
while (Time.unscaledTime < startTime + m_ShotsDurationSeconds)
{
var timeLeft = TimeSpan.FromSeconds(m_ShotsDurationSeconds - (Time.unscaledTime - startTime));
m_TimerText.text = $"{((int)timeLeft.TotalMinutes):00}:{timeLeft.Seconds:00}";
...
this is a basketball minigame. the whole thing is in 100 lines
it's pretty good
i tried to eat my own dogfood here to its greatest extreme
what if you did the whole gameloop as a single task? it's not bad
Dedication!
"there are so many cancellation tokens" - well, those are real. it forced me to deal with everything
I like it
await clock;
https://gist.github.com/doctorpangloss/9758c4bc8abf6c8ff6e9cea6ae9ae111 @compact ingot not bad, not bad at all
if you can read asynchese, you know exactly what happens in this game, in one file
I‘ll have to read that when I’m more awake , hoping to get some ideas
i think this is a crazy way to write a substantive game. but if your whole experience is 2 minutes long, it's perfect
Also fun
you can wrap your head around exactly what happens, and the bugs surface 90% in compile errors, 10% in using cancellation tokens correctly
it forces you to deal with things at compile time
which is really attractive
I once made a game in one huge coroutine, that was less fun
they miss a lot of things
yeah
you can't "await foreach"
you're going to see that and it's crazy
but it is expressive and correct
oh youv'e seen this demo
you can open it on your phone
given a rect of yMin -512 yMax 512 xMin -640 xMax 640, and latitude goes from 0(Npole) to 180(Spole), and longitude goes from 0 to 360 (Greenwich). Take a lat/lon coord and place it inside the rect
go do your homework 
Could it be more obviously homework? Who else uses "given"
People who went through trial by math
How often are GameObjects serialized/deserialized? Pretty rarely, right? 🤔
Doing some custom serialization via OnBefore/OnAfter De/Serialize, trying to gauge how 'hot' those methods are
When they are instantiated and on every edit in the inspector
Oh yeah sorry I mean during gameplay
But that means only once then
Or whenver it needs to be loaded/unloaded
So I can use Linq in these methods without fearing performance 😛
pretty much
Depends when that happens
Right, the stuff I'm doing would only be very slow if it was happening like multiple times per frame or something
usually linq is fine during level/scene init while you show a loading screen, bad if you use it while spawning bullets
lol yeah that makes sense
but generally linq is way less bad that it’s reputation
Linq isn’t slow, the “problem” is that it creates garbage, which may cause dropped frames some time later
Which can slow your application if you're creating excessive amounts and freeing excessive amounts per frame. But it itself isn't too expensive or slow at all.
hey guys do you use some sort of script templates in your projects? for example, it's annoying to create a SceneLoader.cs each time, but writing that script pretty much takes the same amount of time as copying it from your gists... so... you got any tips or tricks for this?
you can create a package
computers are programmed to do millions of things every second. don't sweat it
Can't you make new default projects from the hub too?
As a new template. Sounds like that may be what they're refering to actually
you should try to avoid doing that. if you need to do something to a component's data once, do it in awake
"Common" folder is one approach to this. Folder with all of the various tools you use in projects
package takes time and effort to maintain though
you mean like just a normal folder on your desktop you'd drag and drop to a new project?
Basically. I have mine on github though
Keep the tools separate enough from eachother that you can snag only the tools you need, or grab them all and delete the others
making a package.json isn't that bad
How to detect if 2d or spriterender is overlapping the screen?
Anyone have experience with moq and nunit?
what's the pipeline there, then? same thing with draggin and dropping each time? what if you wanna add something new to it
what's 2d?
a 2d object
so... a game object with a SpriteRenderer, then?
I think you need to define better what you are trying to achieve, though. for example, if one of its pixel is in the camera view, does that count? or - does a bounding box of the sprite renderer count when you check for overlap?
or maybe you wanna check when the whole object is withing the camera planes
I have a puzzle game and we use a sprite render for the puzzle now sometimes when user uploads image with high resolution the puzzle sometime gets to big and some part of goes offscreen.
Basically I just want to detect if the 2d spriterender goes offscrenn.
This is how it should supposed to look like. What im thinking of doing is when program detects that edge of image goes offscreen it reduce its scale so that i would like this
do you need it to be sprite renderer? Image can do this off the table by checking the preserve aspect option
if you need it to be sprite renderer, the way to go is to change the pixel per unit value
Hello Folk, Do you know how to prompt a custom 'authorization denied' message back to the client?
It throws an error and looks like a garbage.
Hi, does anyone know how I can custom sort an array of Tiles based on the color?
Having the Color as an attribute of the Tile object.
I've heard about LINQ and lambda, just not sure how to use them properly
Because Color is not something that I can sort by
you can with linq 🙂
Yeah, but the results might not be as expected
A first would be to know what makes a color "lower" than another one
This can be your own criteria you define yourself
First see if Color already implements IComparable, then that'll make your life easier
Otherwise you'll have to define your own comparison method
Doesn't look like it
Okay, so you can define your own comparison method and use it in a lambda, and Array.Sort that takes in that lambda (in the form of a Comparison<T> delegate)
Array.Sort(items, (i1, i2) => i1.Whatever - i2.Whatever)
for example
What have you tried? This is #archived-code-advanced where debugging, explanations, and more globally a correct question format is expected. Switch to another channel if that doesn't match your question
I am using the Tile object as for i1 and i2, and it has a method called GetColor() yet it doesn't show up.
It shows up, it's just that Comparison<T> delegate expects an int to be returned
I'm sorry I just don't quite understand this stuff completely
Integer value that denotes the comparison between the two elements:
0 if they're the same
1 if the second one is greater than the first one
-1 if the second one is lower than the second one
I do understand that I need my own comparison method though
Do I need to extend a class or something?
Where do I define the custom comparison method?
Nope, all of it can be done in the lambda. The custom comparison is the one you make yourself, in the lambda
In that example it doesn't use a lambda, but rather a full method to do the comparison
I see.
Well the plan I had was to subtract the RGB values from one another, but a better idea is, since I use 4 colors I will determine by myself which one should be the lowest and which one the biggest.
Yep exactly, and that's the part you make yourself. It could be getting the average of the RGB values and comparing that, or a single channel of the color, or the alpha, you choose
Alright then, I'll try it.
Thanks for your help.
How can I handle cases of null values with this?
And have them put at the end of the array.
You can have a special case where if i1 is null, you always return 1, so it gets pushed at the back
How do I add a if condition inside the lambda?
You can't, unless you make it a lambda block statement, or a method
(i1, i2) => {
// statements can now go here
// use 'return' to return values, like in methods
}
Ok
Uff, so I am trying to Build a clean RPG System and I'd like to have my Single Attributes as Scriptable Objects with name, description and icon. Then I have another Scriptable Object which should be a List of Attributes + It's specific value in this instance. I made a Class that has an Attribute and a value property. That i put as a List into the Attribute List Object but It doesn't really work in the Editor like this. Is there a good way to make this work or do I need to do this in a completely different way?
Attributes are Aspects because I was trying stuff with System.Attributes and the naming got confusing
Hello, I'm using Python for Unity 4.0.0pre.1, I've tested simple hello world scripts following the API instructions shared in the documentation (https://docs.unity3d.com/Packages/com.unity.scripting.python@4.0/manual/inProcessAPI.html).
I'd like to use the data processed by the python script in the C# script. For example, the python script will show an array of numbers and I want to do something with those numbers in the C# script.
I thought that I could convert the data to JSON, save it in a file, and then the C# script would read the JSON file and convert it. The problem with this is that initially I tried to do a simple write string into a text file using this
# Write-Overwrites file = open("myfile.txt","w")#write mode file.write("Test") file.close()
But after running the python code I couldn't see the file in assets folder (location of the python script), I'm not sure if it was created, and where it could be.
Any thoughts or recommendations? Doing this differently or a way to solve the current idea I have to implement it if it's a good way to do so?
Thanks
Woww yessir there it is, thank you!
be aware that this package is for editor use ONLY. there is no runtime support
Right, that was one thing I was afraid of since I need to use using UnityEditor.Scripting.Python;, I'll see which other alternatives there might be for runtime support if there is any
you can use that as a starting point^^
they list various possibilities
i don't think organizing something into a filesystem, somewhere, is avoidable.
it's not practical to use python for unity outside the editor environment.
the python program should be in c#
i know that's not really helpful, but trust me
you shouldn't try embedding a python program this way
it's not clear what problem you are trying to solve
you shouldn't try to metaprogram this way
create a single class that is a master data container ([Serializable] class GameEntity {}) and reference it in your scriptable objects as needed class MyAsset : ScriptableObject { GameEntity thisEntity; }
didn't we talk about this?
How am i supposed to do this? The prefabs are naturally "non static" since i have to add them in the editor
@regal olive Don't cross-post
i originally posted in the wrong channel
Then remove it
i was tabbed into gen chat not advanced
done
Also this is a #💻┃code-beginner question. The popup explains it as well
i actually figured it out already, i forgot to make them static
like my other dicts
im just a monkey
How or why really are you referencing prefabs as static? They would not exist at compile time.
they are added in the editro
and it seems to work just fine™️
You can't serialize static fields

I am not metaprogramming. I just have scriptable objects that describe some stuff and want to have a list of those and assign them a number (attributes and their value). And I would like to easily add and remove attributes. I wanna build something that will not become a giant mess of scripts and objects and references but something that is easily editable and creatable. I would love to have this list automatically be populated with all existing attributes that I've created but I can live without that.
hmm
well i don't hear a concrete example of a piece of gameplay in here
when i've looked at RPG asset store assets, the data types are pretty focused
in the grand scheme of things, building a huge abstraction to save you from having to touch a few files to add an "Attribute" (maybe you mean item attributes) is low ROI
Seems like making my prefabs static doesnt let me define them on the editor
how could i define them?
You don't use static to cache prefabs. Initialize them at runtime.
how? can you send me an example
You are trying to initialize instances in the field. Do that on Awake or Start instead
Your dictionary initialization. Your original question. Move that

Visual studio has browned its pants
@regal olive Address further question to #💻┃code-beginner
Yeah, but I wasn't able to use the SortBy, so I tried using a different way
Got it, this is just for a course project from school. Basically we worked on some AI functionalities using Jupyter Notebook and sharing it with the class using colab. The thing is that the project is to create a UI that someone can use it to test things more "pretty". So I was hoping I could create a UI in Unity for this purpose. In case you are wondering, the AI is for a shop and it recomends products to clients and checks a list of comments based on some data to see if they are positive or not, not big deal from the Unity side since it would be just UI and sending some data around.
And since I'm comfortable using Unity I was hoping to create a UI and something the teacher could test and such. But I think I'll look for something else
I got an architecture-ish question.
I am creating a plant mesh generation tool using the advanced mesh API with Jobs. I have nodes that form a hierarchy, and each node has parameters for generating/populating a MeshData.
(Each node would handle like a set of leaves, or flowers, or stems etc.)
Now to my question, when a node has its parameters changed and the mesh needs to update, what would be a good way to do it.
I was thinking of having each node have their own Mesh, and then combine the meshes on export but this feels messy to me, and feels like it would be more expensive.
Another option would be to have a single Mesh and regenerate the entire thing each time via Mesh.AllocateWritableMeshData(..) and Mesh.ApplyAndDisposeWritableMeshData(..).
But that feels also needlessly expensive.
Other ideas or thoughts?
Beyond speed I am also not sure how it handles memory allocation.
is it non-negative matrix factorization collaborative filtering?
bless you
I was thinking of having each node have their own Mesh,
pretty much
how else could it work
combining isn't expensive
presumably you're trying to save time on the latent space to mesh computation
not the mesh to mesh copy
You can use Mesh.AllocateWritableMeshData(..) to create an array of MeshData which could then give each node
can you post or DM a screenshot?
it's perfeclty reasonable but whether it takes 0 or 2 frames to combine won't be that big of a deal
Of what?
of the plant
i don't know, in 3d editing tools 99% of the time, something like XGen is realtime
and it manipulates the whole mesh so it couldn't be that smart about it
Oh, I don't have a plant yet to show. Most of the plants will be really simple though, like under 1k I would assume. If/when I have it support trees, it could go up quite a bit of course because of those leaves.
For recommending products we use association rule to see which products were frequently bought together and then given a product that the client is interested in, it will give products that were bought with product 'selected'.
hmm
can you tell me the name of the thing you're doing from the literature?
or it isn't that
it sounds like "whatever Y is most frequently also bought with X, counting down"
which is called "baseline"
it might be faster to just reimplement it in c#
i feel like it would take you... 20 minutes
i was going to share you my real, in-unity code of a recommender
We have a dataset which you can see it as a list of lists. And each list is like a receipt that the shop has that has strings with item names.
Now, we convert this into a matrix with boolean data that shows which items were purchased (true if purchased, false if not). In this case we only have two receipt.
Then, with an algorithm "priori" we check how often products are purchased.
Then we generate all the association rules. And based on the selected product we get the recommendations from here.
Now indeed, this could be done in C# but the course has to be in Python specifically. At least this part of processing data
the simplest thing would be to use fastapi / flask
and unitywebrequest against your python code
Hey Yall, Im trying to use UnityWebRequest to download a m4a file and play it on a AudioSource. I am trying to use UnityWebRequestMultimedia.GetAudioClip(songMusicURL, AudioType.UNKNOWN); And Then Downloading the file by AudioClip song = DownloadHandlerAudioClip.GetContent(songMusicRequest);
Im getting errors because of the unsupported filetype how could I convert this to the right file?
I want to add critical chance to my game for bullet damage. Would it be too expensive performance wise to have a random value generate for every shot to determine this? Some guns fire over 15 rounds per second. If it is performance heavy, is there an alternative? (Context: mobile game)
Given that you're in #archived-code-advanced, I'll give the advanced answer. You should test it and find out!
Thanks for the help. That's not the advanced answer. Thats the pretentious answer. If you dont wish to help you can ignore, no need for the snark. Obviously i can test it myself on my device but im not doing all the work to implement and then send it to beta testers when someone thats not being pretentious can give me a simple answer. Either rand.value is too inefficient to be called so many times on mobile, or its not.
That's why games most have min requirement's to run.
also googled it second result "No. Random.Range is extremely fast as Unity uses Xorshift128. "
sure, but you don't need to send it to beta testers to determine the answer to that. You need to create a test environment that calls your random function many times per frame (say 1,000,000?) that you can use the profiler to evaluate the performance. You need to build it and deploy it to your target hardware and test the performance on that hardware.
Also, if your game is running at 30 fps, 15 rounds per second is only 1 round every 2 frames.
If you're posting in #archived-code-advanced, people are going to expect you to be able to do basic arithmetic and realize that you're not even calling the function 1x per frame.
in 2021.3 the not keyword is now supported.
would this circumvent the native lifetime check?
if (someComponent is not null)
yes
Ive never seen mobile games limit the devices that can be used
Im trying to make my code as efficient as possible. Calling things once every 2 frames isn't great for performance if there are better options so i asked if anyone knew better options since this is the advanced channel and i expected a real answer like "no unity uses methodology thats about as efficient as you're gonna get for finding random values. Calling it less than once a frame shouldnt impact performance too much."
Or "you can actually do X instead which is much less intensive. With all the other calculations in your game you probably don't want to be doing random value calculations 15-45 times per second."
In the spirit of "not writing the same pattern of code everywhere", would it make sense to extract the typical while(true) { ... yield return new WaitForSeconds(Time.deltaTime) } into a separate function? For example:
private IEnumerator LightColorBounce()
{
while(true)
{
SetColor(Color.Lerp(Color.red, Color.grey, 2 * Mathf.Abs((Time.time % blinkPeriod / blinkPeriod) - 0.5f)));
yield return new WaitForSeconds(Time.deltaTime);
}
}
becomes
private IEnumerator LightColorBounce()
{
RepeatEveryFrame(()=>
{
SetColor(Color.Lerp(Color.red, Color.grey, 2 * Mathf.Abs((Time.time % blinkPeriod / blinkPeriod) - 0.5f)));
});
}
why would you wait for Time.deltaTime?
i could be wrong but i thought that's the proper way to do something each frame, like lerping the color of a material
yield return null will wait for a frame. new WaitForSeconds(Time.deltaTime); would wait for the time the last frame ran, and would allocate while doing it
what does this change? startcoroutine have the waiting functionality built in?
oh ok
so the coroutine runs once per frame by default
how is yielding related to the framerate?
my understanding is that an IEnumerator just runs whenever you ask it to using MoveNext() and the yield return is the value .current gives you. I would imagine the functionality to only call MoveNext() once per frame is inside of StartCoroutine()
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
Yielding of any type, including null, results in the execution coming back on a later frame, unless the coroutine is stopped or has completed.
so you're correct about the yield return null behavior, but it would seem that it's the implementation of StartCoroutine() that makes it continue on the next frame. waiting for more time would just be every other frame or whatever
there are other YieldInstructions that break from the normal Update cycle. WaitForFixedUpdate, WaitForEndOfFrame, etc
Of course how Unity handles StartCoroutine is what makes it do what it does 🤷
When you yield Unity will evaluate that and come back on a later frame.
Yielding for null is how you wait one frame. That's it 🤷
i just wanted to clarify that just in case i was misunderstanding it and that if i were to use an IEnumerator in a way that isn't a coroutine, then my understanding of yield return null would be correct
sure
sorry if it was pedantic, i just wanted to double check whether it was the yielding itself that waited 1 frame, or if it was the idiosyncratic way unity uses it
what is the use case of WaitForEndOfFrame vs null?
You can use it to read the display into a Texture, encode it as an image file (see Texture2D.ReadPixels and Texture2D.Texture2D) and store it on a device.
yeah just intuitively i thought that "before the next frame" is the same thing as "after the current frame". the difference is that Update(), input, and physics happen between one way, and then game logic and rendering is in between the other way
thanks
if it doesnt matter when during the order it happens, i guess null is just the de facto choice
"generating random values generally isnt considered an extremely expensive operation but you'll obviously want to test out if calling it 45 times a second effects performance. Nothing else will perform better so you'd have to choose another way to implement crit chance if it is affecting performance"
would have been a simple answer that didnt require any sass.
Poor man asking for help here🥲
Right now i have a debug script which executes in editor mode. It will create a game object during its life scope. And I want to let the lifescope of the created GO matches the debug script. (the Destroy() logic is inside dispose())
Now the problem is that every time I recompile the codes, the domain reloads I assume, which resets the state of the script and it will create a new GO again after compilation. However the GO it created before is never destroyed (seems like reloading the domain won't trigger Dispose() on objects) and the GO keeps stacking up.
My question is that is there a way to properly destroy the GO when compilation happens (or any other thing that will "reset" the state of the script due to domain reload i assume)
ok setting the GO to DontSave kinda help
but it still requires the user to manually re-launch unity to clean the stuff
I dont think Unity really does dispose. You could look at some of the callbacks in EditorApplication, there are a few on domain reload. Doesnt your script also get OnDisable?
Ah, I don’t know OnDisable() will be called under this scenario. Lemme try that
you can also use this https://docs.unity3d.com/ScriptReference/AssemblyReloadEvents.html
Does anyone know how ContentSizeFitter calculates preferred width/height?
Because the store does not show you games your phone cant play
the source code is available for it
Yeah, but it simply calls Layout.GetPreferredWidth (or something like that)
That said, apparently, it iterates over each element in the game object searching for their width/height and return the largest
Anyone know if it's possible to use ExcludeFromCodeCoverage (https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.excludefromcodecoverageattribute?view=net-6.0) attribute to tell the code coverage package to ignore certain classes/methods?
Or if there are any alternatives?
Found it. We can use [ExcludeFromCoverage] from UnityEngine.TestTools
What? Lol dude i wasnt taking you out of context. I wasnt even quoting you. I was saying what a good answer to my question would have been using part of your explanantion. I did not imply you said the answer.
You are completely misunderstanding what that last message was about. And no im not an idiot so i wouldnt be dumb enough to ask a question i knew the answer to. Literally in that message you're quoting, I gave examples of what a good answer to my question would have been, which i was looking for. I thought it'd be pretty simple for an "Advanced" unity dev to answer either way whether it was too inefficient or if it was the most efficient option and should be fine performance wise. Instead I got snark because many devs like to talk down to other people asking questions.
have any of you encountered this issue before (or something like it)?
- create a prefab variant (and git commit the variant)
- add an instance of that variant to your scene (and git commit the change)
- perform a git rebase to squash commit #2 into commit #1
—Step 3 changes the GUID of the prefab variant and breaks the prefab reference for the object from Step 2?
it's not strictly necessary for me to rebase this particular commit, but I'm concerned that if I rebase in the future it might break the references again.
i don't see how a git rebase could change the guid
you could try quitting unity
ah, not during the rebase
I'll give that a try
it is very weird but clearly happening when I rebase
I have this for loop to spawn buttons and assign actions to it: (I simplified it here)
for(int i = 0; i < 10; i++)
{
ButtonGameObject.GetComponent<Button>().onClick.AddListener(delegate { ButtonAction(i);});
}
But the button always returns i = 10.
Any suggestion on how to get the actual 'i' I assigned to it?
you will need to make a new local variable that you assign the number too
then use the local copy in the deltate
ok that makes sense, thank you!
hi anyone can help please,i updated my visual studio to the 2022 version but now i can't see the types of some variables, they aren't colored, just white. anyone knows how to fix this? ty
#854851968446365696 to configure it. also not an advanced topic
Reloading the solution helps usually
I think you can find it in the top left part of the menu. "Close solution" and then re-open it manually again
Hey can someone help me with a lens flare issue? I am using URP but the Lens Flare (SRP) component doesn't show up?
where are you looking for it
In the add component button on an empty game object
all i see is the normal one. I checked the rendering tab but I mainly just search for things by name. But both cases its not showing up
I am using URP 10.3.2
And I opened this project in non URP but then added it later
Not advanced. You might wanna look into IPointerClickHandler, etc for setting up dragging: https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.IPointerClickHandler.html
You're fine, that's the answer though
Ok thanks
There's also IPointerDragHandler or something too you'll need
Anyone know why the Lens Flare (SRP) component wont show up on my URP project?
This is a coding channel
we can address components in this channel
Don’t be surprised if you don’t get answers on this channel tho, sounds far from scope of this channel
isn't those events just for UI?
Think so
Yeah, so can't use
not sure if this would be considered advanced, but im trying to make it so my audio clips volume fades out very quickly instead of stopping instantly with audioSource.Stop(). for context im working with undertale/typewrtier style dialogue with sound effects and i currently am running a loop that stops the last audio before playing the next one and its creating a small popping sound every time its cut off atm
is there an easy way to do this or would i need to make a separate function/coroutine of some sort
I’m not sure but this might help https://johnleonardfrench.com/how-to-fade-audio-in-unity-i-tested-every-method-this-ones-the-best/
thanks ill check it out
use a PhysicsRaycaster3D. EventSystem works for 2D and 3D
no you can use them for objects with colliders too
you just need to have the right components in the scene
i'm very confused regarding how to destroy gameobjects under editor mode.
i first tried Destroy(), and it throws out the following error:
So then I switched to DestroyImmediate() and it throws out another error:
how am i gonna Destroy an game object then...
I would probably do EditorApplication.delayCall () => DestroyImmediate(thing);
lemme try that
Can someone give a advice about how to batch skinned mesh renderers ? I tried Mesh Baker but in some situations i need to update mesh so its not for me i guess I tried animation instanceing but that package give me an error when targeting mobile and also tried to SRP batcher but not covers the skinned meshes
You dont batch skinned meshes. You bake the animation into what is called a vertex animation texture, you make a instanced shader that offsets the meshs verticies based on the texture and you draw the meshes with DrawInstancedIndirct. This is the way to get thousands of animated meshes. Some mobile platforms wont even support instancing like this
I found this https://assetstore.unity.com/packages/tools/animation/gpu-instancer-crowd-animations-145114#releases let me try
"Mobile support is designed for high-end devices and currently at an experimental stage" I would not buy two assets just to find out that my target platforms are not supported
Why do you even want to do crowds on mobile ?
In some part of mechanic i need to render hundreds of low poly characters (very low tris count) so i need to optimize it somehow
I saw these vertex shader tech. yesterday other than that ı dont know how can i optimize it for mobile
Its not a trivial issue to solve
The simplest way is to bake to a vertex animation texture do get rid of the perf cost of a skinned mesh and let unity handle the batching
Gpu instancing is not really friendly to mobile
I dont have knowledge about vertex animation thing
but i will search doc or article about that
thanks a lot i will move on your road
This is a good start
The Vertex Animation Texture (VAT) technique consists of baking animations into a texture map for use later in the vertex shader.
Thanks a lot i will share the results i hope 😄
Gl
@livid kraken I'm starting to get stuck already 😄
I dont know what i am doing wrong but ı guess in some points of my fucntions are incorrect they why they didnt give any sample or something like that : D the above texture is theirs and other is mine
{
Mesh meshState = new Mesh();
TargetAnimator.Play("IDLE", 0 , (1/TargetClip.frameRate)*frame);
TargetAnimator.speed = 0f;
TargetSMR.BakeMesh(meshState,true);
return meshState;
}```
{
Matrix4x4 localToWorld = transform.localToWorldMatrix;
Vector3[] vertices = new Vector3[mesh.vertices.Length];
for (int i = 0; i < mesh.vertices.Length; i++)
{
vertices[i] = localToWorld.MultiplyPoint3x4(mesh.vertices[i]);
}
return vertices;
} ```
I would appreciate if you let me know if there is an error that catches your eye.
I dont really have the time now but I dont remember converting the vertices to world space when I was doing it
Don't call mesh.vertices multiple times. Do it once and cache it. It creates a fresh array copy of all the vertices every time you call it
you can try the asset just ask for a refund if it doesn't work
in principle iOS devices can support it if macos does
and android vulkan
Anyone familiar with mapbox and photon for multiplayer spawning? I want to spawn players at their GPS location in a multiplayer GPS game. I heard about having to use Class Conversions maybe, but I'm lost on how they work. Any help would be appreciated.
Is it possible to schedule batches of raycast commands from within a job? Trying to perform some raycastcommands, get the results, and perform some work from the results all in one job.
A blog post from Lidia Martinez seems to indicate this is possible? http://blog.lidia-martinez.com/use-the-results-of-raycastcommand-schedule-on-a-job Unfortunately, it could really have used a final example that pulls it all together
When just checking if a type is another given type or not, is it better to use GetType and typeof like this:
if (someClass.GetType() == typeof(someOtherClass))
or use pattern matching (is this the correct term?) like this:
if(someClass is someOtherClass)
I ask because I think the second one boxes it, right? And the first one does type manipulation stuff, probably creating a little garbage (or does it). I'm not sure if there's much difference in either case, but curious if so. I prefer the second as it's much more readable imo, but worried about boxing a big class. I'm not sure if the size of the class matters at all during boxing, if it's even happening here
For context, I'm trying to disable a list of abilities on an object. Movement is an ability. I just need to know IF one of these abilities is movement, and stop input if that's the case.
It's not boxing unless you do x is Interface y where x is a struct
Just is shouldn't be allocating
And second one is generally considered better unless you need some very specific info from the type
I.e. does it inherit from a type
its also very situational if your class implements inheritance.
first option will be true only for exact class.
second option will also be true if object reference is a child, but youre matching it against the base class
Wondering if someone could help me with something
In the editor I’m copying an external script in , normal via FileUtils. Then trying to invoke a method via reflection
The reflection error with NullReferenceException
Runs the script again deleting and coping back the same file it works
Share some code
Making me feel like i need some sort of reload refresh
O one sec let me past some code
This is in editor in unsaved scene
{
AssetDatabase.Refresh();
for (int i = 0; i < overrideDescriptor.afterSceneBuild.scriptPaths.Length; ++i)
{
string sourceFilePath = overrideDescriptor.afterSceneBuild.scriptPaths[i];
string targetFilePath =
Application.dataPath +
"/Bla/"+
ParseFilePath.ToFile( overrideDescriptor.afterSceneBuild.scriptPaths[i], ParseFilePath.ReturnFile.FullFileName);
var assetsPath =
pathAsset+
ParseFilePath.ToFile( overrideDescriptor.afterSceneBuild.scriptPaths[i], ParseFilePath.ReturnFile.FileNameWithoutExt) +
ParseFilePath.ToFile( overrideDescriptor.afterSceneBuild.scriptPaths[i], ParseFilePath.ReturnFile.FileExt);
FileUtil.CopyFileOrDirectory(sourceFilePath, targetFilePath);
AssetDatabase.ImportAsset(assetsPath, ImportAssetOptions.ForceUpdate);
}
AssetDatabase.Refresh();
CompilationPipeline.RequestScriptCompilation();
AssetDatabase.Refresh();
Type t = Type.GetType(" com.bla.Editor.BlaBla, Assembly-CSharp");
MethodInfo method = t.GetMethod("BlaMethod", BindingFlags.Static | BindingFlags.Public);
method.Invoke(null, null);
}```
Sorry super messy
RequestScriptCompilation is async and thus won't be done reloading when you try to use reflection
I threw in refresh all over the place
Besides, if the domain gets reloaded then your code will likely not be executing anymore
That ok this just need to run in editor
Once
Wait I miss read what you said
Ok so how can I do this , in editor
Subscribe to some callback that triggers after domain reload and then do your magic if needed
Do you have a example? Are then any in unity callbacks that you ca n recommend or an attribute I can add to the method on the script I’m importing
All static methods
Basically I just need a method to fire on the script a line after importing the script
Is there a way to yeild return until reloading is complete
There's a compiliation completed callback somewhere
But that might also not work since the domain is thrown away
It's pretty hard to do in general
How does unity know if a script has been reimported vs a new script created ?
Every asset in Unity has its own .meta file that contains a unique GUID. New scripts won't have a .meta file yet.
wdym reload?
so this is in StateMachineBehaviour that is on a single animation controllers state.
{
if(!stateInfo.loop)Destroy(animator.gameObject, stateInfo.length);
}```
i need to destroy the whole gameobject when the anim ends only if the animation is set to not loop
this doesn't work
is the animator gameobject never null?
have you tried removing the delay / stateInfo.length?
that's the thing i think it checks if the state is looping not if the animation clip assigned to the state is set to loop
and i have no idea how to get it
ah ye, you are sure that the function gets called and there are not base calls missing
you might be able to get the animator current state from the animator, but that would be a bit of a work around
What didn't work about this solution?
Did you try putting it in OnStateExit?
Hi! Anyone know how to solve this issue? I have just got when i introduced the AI experimental package. Any way to dump/free allocated memory?
you can ignore those errors. try restarting your editor
based on the look of this code, you have a bug somewhere. you should use an editor like Rider, and use braces on your if statements
what are you trying to test?
what's the purpose of all of this?
you should use is
there isn't any errors
onstateexit wont be called because it is attached to a single state without any exits.\
It didnt work because stateInfo.loop gets the state loop status not the animation clip
Did you try with OnStateUpdate instead, i.e.
public override void OnStateUpdate( Animator animator, AnimatorStateInfo stateInfo, int layerIndex )
{
base.OnStateUpdate( animator, stateInfo, layerIndex );
if(!stateInfo.loop && stateInfo.normalizedTime >= 1.0f )
{
// Destroy here
}
}
it seems like what you're trying to do is really fidgety
what is your objective?
you can't use the animation state machine for gameplay implementation
it's too arcane
you'll have too many bugs
player launches a object with a combo. I instatiate the object, apply speed to it and based on the animation (a lot of different animations for characters and different combos) i want to destroy it on animation end if the animation clip is not looped and let it fly if the animation clip is looped
Thanks, i'll try this, but i doubt it will work.
Should work 🙂 Does for me, let me know
thank you, i will.
oh yeah, you're trying to do that kind of combat game
this is going to be hard 😦
yeah 😄 a pain in the ass
if @stray plinth answer doesnt work i think i'll get the statebehaviour script in my monobehaviour code and just set a variable if it is looped or not
thanks guys
have you looked at an asset store asset for this sort of thing?
have we already discussed this?
i don't remember
from first principles, you can just use frames counts and assume the application runs at 60fps or whatever, and you will be fine setting up this kind of game
where the speed issues don't matter for less than 60fps
like where you just fix your game until it performs well enough to exceed 60fps
or use a logical timestep of 30fps (i.e., out of every 30 to 60 frames rendered, choose 30 to timestep your game)
hmm, maybe but that will require quite a lot of painfull work to write every animation time in frames
i'll try to automate it
yeah
well that's the downisde of these games
where to save at local on webgl. please. application.persistent data path is not working
Please ❤️
file. to Save/Load data
Webgl Game
you need to use web requests to read/write files in webgl
persistentDataPath works file as the location
so i have a simple perlin terrain generator which makes a 20x20 surface terrain mesh, however i want a 20x20x20 cave mesh. how would i go about doing this?
some form of meshing algorithm like marching cubes that takes a signed distance field as input
ah alr
use playeprefs for small saves
and how might i do that?
clayxels / mudbun (assetstore) or learn how to make a voxel engine yourself
alr
those assets only work for small scale things, but 20x20x20 is right in their ballpark
how can I do that?
It is not small
@undone coral the purpose is trying to use unity in a more traditional vfx pipeline. No build needed just scene assembly and recording frames. In a traditional pipeline you inject script during various time. I’m trying to get that same behavior in unity by having delegate sitting at different stages of a scene build. New scripts outside the project are copied in and self assign to the appropriate invocation list depending when a artist wants to execute the script
The problems I’m running into are forcing assembly reloads and setting up a callbacks addi g to delegate invocation list
the purpose is trying to use unity in a more traditional vfx pipeline
hmm..
I know
is there a vehicle rendered in your scene?
?
No
Not fashion
why would you inject scripts at all
Just pain
like why not just... add the .cs file
to the assets folder
etc. etc.
what is the idea
an artist isn't going to know how to use any of this stuff, so you might as well make the exact UI for the exact bespoke thing they want to do
and implement it as simply as possible
The cs file are unknown
it sounds like you have all the disadvantages of having a way to build the project
with all the disadvantages of trying to program at runtime instead of buildtime
it's bonkers
who's idea was this
Only thing that is know is it will use a giving delegate
you're going to say the word delegate to a graphic designer?
They are all technical
New scripts outside the project are copied in and self assign to the appropriate invocation list depending when a artist wants to execute the script
in the editor, there's[Initialize]
at runtime, there's [RuntimeInitializeOnLoad]
it sounds like you are reinventing one of these two attributes
I saw that late last night
c'mon dude
But the issue is still getting the assemble reload
why would you need to worry about that
i don't understand why if the .cs file is present in the Assets/ folder
and if it's not, why isn't it?
why would you start the editor, headlessly, then add a dll file... why do all of that
it makes no sense
maybe if you gave me a concrete example of what the idea is here
is this to procedurally generate graphics of some kind?
like what is the concrete application?
the only traditional VFX pipeline this makes sense for is some kind of ad / product photography
where it's product customizations or whatever
otherwise i would not be able to reason why to do this in unity at all
or some kind of game inventory
like it's animatics for a game that already exists in unity
then again... why pilot it from the command line
it would help me a lot to know what the real application is
lol
i'm concerned this is taking a while
i think you can give me a logline
i have been doing my work in the background 🍿
So in a traditional vfx pipe you have not project folder equivalent to unity project folder. To add permutations to a shot for example you write you python code and at offline render time all tbe various code execute
Allowing you to scale permutations 1000x
It in that vein
okay
but what is the actual project?
it's not conceivable the artists would need this level of flexibility
it would really help to understand what it is
because i can help you identify the exact minimum piece of code you need
i do vfx, and build pipelines
i run a unity builder service
is it a crypto thing?
are you doing an NFT blah blah?
it's okay if the answer is yes @brittle pumice
I’m just sensing frustration from you. I appreciate you taking the time to chip in, I’m going to run a few more test base on some of your suggestions
no no frustration
i can't help unless i know what it is
Fair enough, I’m also limited it what I can share. I think I need to rethink some things, been a long night
okay well let's say it's a bunch of avatars for an NFT project
and you want to render some kind of video for them
you would... write the script to do this. everything should be set up in the editor
let's say this is for some kind of ad where the end user makes user generated content
you would... write the script to do this. everything should be set up in the editor
do you see what i mean?
let's say this is for a steam workshop sort of deal. people are making UGC unity assets
i don' tknow. whatever. you would still write a script ot do this direct4ly
so do you see why i'm struggling to understand how this fits in? you say VFX pipeline, but that makes no sense. you gotta help me out here
it happens that i am working with someone who is working with a guy named francois, and i think it's just a coincidence @brittle pumice
which would make sense for your problem description
lol
Not impossible but unlikely
I really dont know how to script when four of these game objects are at max health (https://gdl.space/hesolegane.cpp) I want a boss to appear. Here is another script (https://gdl.space/imixohorer.cpp) unfinished.
Is reflection the right way to turn special keywords from a text into their actual ingame values? Or is there another preferred alternative?
I essentially rolled up my own localisation system and I'm trying to figure out how is the proper way to replace the values
if it helps, I have a singleton manager that handles localization
it has an scriptable object with all of the text entries of the game with all of the languages , separated by a dictionary key
so everything on the game that uses texts has some kind of script that checks if the language changed, and if it did, updates the text
Yeah, I mean.. I got that part working
But how do you handle, for instance, a text that says "This upgrade costs X"?
Currently, in my localized file I have "This upgrade costs {cost}", but I'm not sure how to replace "{cost}" with the actual property value
We use separate entries for those
Mind explaining a bit more?
instead of using a single TMPro for example
we use 2
or more, depends on what we are doing
And then you use a script that sets the value of the second TMPro based on the property value?
yup, with that said, we didnt use that many of the type of messages that need parsing. You could also tell translators to leave some stuff like that untranslated
and you could do a simple replace
Thats my personal experience at least, somebody else might have created their own approach haha
but yeah tldr separate tmps is what we did
Hey guys I have very weird question that I gain nothing by googling
If you have some docs/blog post I would love to read it
Thanks! I'll give it a try
One of the games I am playing which made by unity, downloads patches without updating from appstore. I dont know if its the illusion of patch or not.
Is it possible to change the client code in iPhone without making real update from appstore?
If so how does this happen?
serialized data most likely?
I don't think so. What I think they're doing is not updating code, but instead, updating data files that the code is already prepared to read from
For instance, the game already knows how to interpret an event data, so in order to make a new event, they simply need the client to download the data
The size of these thing can vary between couple of hundreds kb and 50mbs. My junior mind cannot understand how data files can be that big.
Images, videos, audio, all of that can get pretty big pretty fast
😕 so the code architecture should be really good to handle these situations I guess
Sort of.. I mean, without any concrete example, it's hard to say, but taking the event example I gave
The code checks at a given time if there's a file called "event.data" (which is only downloaded when an event is ongoing)
The programmers of the game knew beforehand the structure of the evet.data file, so they basically wrote a parser for the data present in it
For instance, the first line is a structure that tells which images need to be loaded in the event banner that will pop up when the player loads into the game
Another line might tell about the music, and yet another might tell about the powerups
It's really a matter of serializing/deserializing data in the appropriate way
Hmm I see. This can also be done to heroes’ damage health thing for example. Without really updating from app store one can change the data that reads heroes’ property. With a so called ‘patch’ heroes can have different attributes.
Thanks a lot!
For [Flags] enums, adding a flag is &= and removing a flag is |=
Correct?
🤔
I think it might be the other way around 
I guess remove is ^= 
Apparently it's &= ~X 🤮
|= X is to add, &= ~X is to remove
has anyone ever seen
Error when executing git command. fatal: not in a git directory
when building a project that references git repositories in its packages.json?
also, is there a way to register events with EventSystem on the "background"? is the only option a "catcher" rectangle in the background?
Catcher is the simplest way yeah
how about for stuff that has colliders but no other event handlers?
for example, i have a big ol terrain
i was thinking to have two physics raycaster 3ds, one for the background layer only, and then a normal one
but i'm not sure how that'll play out
I have a question in relation to FixedUpdate.
When exactly the ApplyForce methods are applied? because I am needing to calculate velocity like this:
_velocity = (CurrentLiftPointPosition - _lastFramePosition) / Time.fixedDeltaTime;
_lastFramePosition = CurrentLiftPointPosition;
_velocityMagnitude = _velocity.magnitude;
_localVelocity = _aircraft.transform.InverseTransformVector(_velocity);
_velocitySquared = _velocityMagnitude * _velocityMagnitude;```
CurrentLiftPosition being = `Vector3 CurrentLiftPointPosition { get => _aircraft.transform.TransformPoint(_liftPoint); }`
It works perfectly fine if I don't apply any force watsoever, but when I do, everything spazzes out at one point, what could the problem be?
Also, I apply forces mostly trough:
```cs
_aircraftRigidbody.AddForceAtPosition(_liftForceVector, CurrentLiftPointPosition);
Could I create new object of unknown class inherited form abstact class?
don't cross-post . . .
is it possible to differentiate between a click count of 1 on the way to 2 clicks with event system + input system?
so far i am seeing, no.
like, double clicking?
I imagine you would need to write a custom Interaction that checked that you pressed and didn't double click during that press duration
Usually most things want to accept clicking instantaneously and will just perform the action regardless of the double-click
because having delayed clicks because you could double-click is a bit eh
i used the unirx solution
unirx isn't worth nowadays imho... it's too bloated
it also boils down to defining a smart user experience.
most of your single slick actions should be passive. for ex, when single click is performed it shouldn't do some drastic changes to the ui. with that you can simply trigger the single click immediately, and if double click is detected, you can just trigger double click action again.
if you add delay to single click until duble click timer expires, its a bad experience for user and would give a delayed response to them
public async Task<IDataResult<BaseUser?>> Get(string userId)
{
return new SuccessDataResult<BaseUser?>(await _iBaseUserDal.Get(x => x.UserId == userId));
}```
Hello. Do you think using ? operator for null operation is a good practice?
I am worrying about using too much could cause maintaning issue. What do you think
It makes perfect sense to use nullables where the values can actually be null, whether your type is a struct (all versions) or a reference type (NRT - C# 8+)
Makes the code safer by forcing you to take in consideration the cases where the value isn't present
var resultPhone = await _endUserService.CheckByPhone(phone.Phone);
if (!resultPhone.Success)
{
return new ErrorDataResult<User>(resultPhone.Message);
}
await _oneTimePasswordService.DeleteAll(phone.Phone);
var newOTPCode = _oneTimePasswordService.GenerateCode().ToUpper();
OneTimePassword newPassObj = new OneTimePassword()
{
Phone = phone.Phone,
IsConsumed = false,
CreationDateTime = DateTime.Now,
ValidationEndDateTime = DateTime.Now.AddMinutes(1),
OTP = newOTPCode,
};
await _oneTimePasswordService.Add(newPassObj);```
My next curiosity is if I need to check all returning objects if it was successfull to proceed?
Drag-drop into your assets, it'll check if the versions match and throw an exception if it doesn't
var uiSettings = new Windows.UI.ViewManagement.UISettings();
var color = uiSettings.GetColorValue(
Windows.UI.ViewManagement.UIColorType.Background
);
return color.ToString();
I wanna use this method and it throws me the error
The type or namespace name 'Windows' could not be found (are you missing a using directive or an assembly reference?)
My target platform is android. However this script is in an "Editor" folder
The error should be fixed if I import the windows .dll right?
this just throws me an 'Player script does not have an variable called [variable name]', maybe because this line T playerScript = player.GetComponent<T>(); is using T the wrong way but not sure how to properly use it
if i put T as a argument like this hi(T component, other variables) the T playerScript = player.GetComponent<component>(); won't work even with a typeof or .GetType()
(oh and im trying to edit a value of an variable by the name on another script)
is it possible to check if an array contains an object of a certain type?
in a simple expression like oneliner?
LINQ is a good starting point for querrys over lists or array
Yeah i was thinking about that. Just wondering if there was another way I could be missing
I have Array.Exists<T>(T[], Predicate<T>) on my side
Array.TrueForAll(myArray, x => x.age == 12); make sure to import System.Linq
x is the item in the array
So a one-liner type check would be something along these lines
Array.Exists(arr, item => item is OfACertainType);
if x.age == 12 is true the function will also return true
oh whoops thought he meant value not type
btw can I simply extract that item to use inside of my if or do I need to make another search in there?
You'll have to use LINQ for that
another query so?
Look into .FirstOrDefault, accepts a lambda, and returns the first item that matches the predicate, or default if it wasn't found
Can combine both in one here
Not found = returns null or whatever the default value is for that type, check it in a if statement
Oh, array has that integrated lol
T item = Array.Find(arr, item => item is OfType);
if (item == null)
//...
Ah yeah because RaycastHit is a value type, that can't be null
Check hit.gameObject == null, or hit == default
figured it out just needed to get the field not the property
well for some reason this isn't working for me...
is there a better way I can check if an object is of a certain type? or am I doing it wrong?
I didn't want to iterate through all objects and try get component
You'll have to TryGetComponent
public static IResult Run(params IResult[] logics)
{
foreach (IResult result in logics)
{
if (!result.Success)
{
return result;
}
}
return null;
}```
Hey people! Do you have any idea how I could use async for foreach?
Thanks
well any idea why my hit variable isn't updating on the if == null scenario?
ps: i found out it was because of the hitCollider variable, but still don't know why
Hello, I am currently moving gameobjects with coroutines using something like that
float curTime = 0.0f;
do
{
var percent = Mathf.InverseLerp(0.0f, duration, curTime);
var newPos = Vector3.LerpUnclamped(startPosition, endPosition, moveAnimationCurve.Evaluate(percent));
transform.position = newPos;
yield return new WaitForEndOfFrame();
curTime += Time.deltaTime;
} while(curTime < duration);
And what I want to do now is be able to speed up this animation while it is running, but I am having trouble seeing the best way to do so
I thought about shortening the duration but it just makes the animation jump forward because the InverseLerp will not be smooth between the frame with the old duration and the new one
Add a multiplier to curTime += Time.deltaTime
thanks !
Is there any problem with having multiple canvases at once ? (for example one canvas per scene and using additive scene load)
And it's actually recommended to have multiple canvas, as updating a canvas element might redraw the whole canvas [citation needed]
How can I order an array of gameobjects based on it's layer.
What i'm trying to achieve is an array that is ordered based on a priority, so I want all objects from a certain layer first then the second layer then the third etc...
I was thinking about using the orderby but what should be my compare function?
How would I translate the blue arrow to the green arrow using the red arrow, I want to move the player along the ground normal
i'm not understanding your problem sorry 😅 Do you pretend to simply move the character along the ramp?
Why not using playercontroller? I believe it deals with those situations
No, you have to manually move the player controller along the ramp
hello there can i ask UnityEditor questions here??
at least with the normal move function
If they are code related ye
this is my code when i try to import the prefab
it wont accept it
This worked for me
pls help me 🥲
how does your code know what car it is?
do you get the selected object?
i define the car?
i meant select it
Morning!
https://docs.unity3d.com/2021.3/Documentation/Manual/roslyn-analyzers.html
According to this I need to add a tag to code generators. But there seams to be no such option when the generators should be part of a pacakge
can someone tell me what "Instantiate.Produce" in the profiler is doing?
in my experience on mobile, there's
90% of users
tap in the middle
of the screen repeatedly,
unless the interface is exactly
the same as instagram, in
which case they scroll
9% of users
try to interact with the
interface experimentally
but get frustrated anyway
1% of users
enjoy the interactions
presented
i am trying to deal with the kind of user who taps repeatedly and give them a big feedback
because that's about as much as their monkey brains can handle
you can project the blue arrow onto the plane defined by the red arrow. you can also take the cross product of the character's right (instead of forward) and the terrain normal. lots of ways to do this. but you probably want to use the right character controller instead
does anyone have an idea why ztest isn't working on shadergraph shaders?
i'm trying to make an outline for occluded objects but it seems like it isn't working for the occluded parts of my object
you need to generate meta files for your package, so you'll have to add them to a project where you can change the tag, then just copy everything back to your package
that is quite stupid....
will it run the generator for both srcipts in assets and the package?
does anyone know why things like position constraints and getting the actual transform position of objects affected by AnimatorIK will have their positions properly show in scene/game view but anything tracking them won't?
I've tried GetBoneTransform, the actual GO, and a few other methods.
Are there any downsides to loading tiles into a Tilemap via SetTile and SetTiles vs having the whole Tilemap and all tiles load when the scene load?
I'm planning to load my levels from text files and then setup the Tilemap during runtime but I'm afraid it would affect performance
I'm just guessing, but SetTile/SetTiles is probably slower, but it gives you flexibility to do all kinds of things you could do otherwise
like loading from text files
you could set up a pipeline that does all the tilemap building work at edit time
still load from text files, but have an editor tool that loads them then saves as a normal tilemap
but honestly, loading screens aren't that bad. If you're just doing it while loading the level the performance is probably not much of an issue
Awesome! Thank your for the answer! As you say the flexibility is very nice and I would only use it during loading screens so it might not be a problem, pipelines sounds interesting as well
a good option if loading screens turn out to be too long
also, maybe just find one of unity's tilemap assets and open it in a text editor to see how they're saving it. It may be easy to just have your text files be interchangeable with theirs.
thats a good idea, going to use it for building a level editor so might need my own format but knowing how they do it could be really useful
@cedar ledge This worked for me
would that be more efficient
Nah I'm wrong my b
is there a way to get addressables to work on ios?
There is no reason why they shouldn't work. What's your error?
no error in unity, but in xcode it gives addressables the key squareapple and makes them unloadable
Page changing to: StartUp Ustyler.Behaviours.UI.UIManagers.<SwitchPage>d__31:MoveNext() System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start(TStateMachine&) Ustyler.Behaviours.UI.UIManagers.UIManager:SwitchPage(PageBehaviourType)
Unloading 6 unused Assets to reduce memory usage. Loaded Objects now: 7826. Total: 9.534333 ms (FindLiveObjects: 0.257750 ms CreateObjectMapping: 0.127042 ms MarkObjects: 9.084500 ms DeleteObjects: 0.064458 ms)
ArgumentException: An item with the same key has already been added. Key: SquareApple at System.Collections.Generic.Dictionary2[TKey,TValue].TryInsert (TKey key, TValue value, System.Collections.Generic.InsertionBehavior behavior)`
though in unity the script asset pack group schema cannot be loaded
so I think that is the cause
which would suggest a compilation error, but there arent any I can see
anyone got any experience with math parsers or something sinmilar i could use here?
essentially i want to have a lot of flexibility when it comes to designing my ais, and that includes the direction every bullet is shot. sometimes thats a fixed value, sometimes thats at the player, potentially with an offset, but sometimes i may want to do it based on time, or sin time etc. without having a million checkboxes
my idea is a string field where i can put something like $PLAYER + 90 or Sin($TIME / 2) * 90
it's probably easier to just write that in code rather than the inspector
yes but how would i interface that
how would i then be able to choose which to use
or maybe different shoot behaviours depending on what type of expression im using?
so one thats like FixedAngleShoot and one thats SinTimeShoot or something
i suppose it could work
That sorta thing is usually done by like, a dropdown to select Value where you enter a literal value of 90, or some other option and the editor will show an object field. Could use a scriptable Object or something to drag into this, to spit out a value or perform some operation on it. I think Game Creator does their numbers this way, similar to what you're wanting
Yeah, think something like this would work for you: https://docs.gamecreator.one/stats/stats/stats-overview/formulas
Not saying use GC, but the idea they're using here fits I think
hello im a beginner coder, and ive never coded before (besides lua but not much). how would i correct errors in a unity project? (the project in question is HyperEngine by CodeParade)
Start by reading the #854851968446365696 then going to #💻┃code-beginner and posting your code, using the guidelines in the readme, with your question
okei
im getting this on several of my asset pack group schemas
I cannot see an error in the console that would be causing this
could reinstalling addressables help?
a reinstall did not help
is there anything im missing with addressables? its just I cannot see a reason why this would be happening, and im currently going off by best assumption of what will solve this problem based on the missing assetpackgroupschema script reference.
ive tried now removing that file for one of the groups to see if it has made a difference, but I wont know til a build has been done, which does give a very slow turn around with debugging problems
Tried a build and nothing
still the same problem
doesthe squareapple key mean anything in xcode?
do you only have the problem for iOS? Have you tried windows?
not sure if you've seen this already: https://forum.unity.com/threads/addressables-work-when-running-in-editor-but-not-on-ios-build.780614/
only ios as far as I know
my co worker can build to android and run it on android fine
I cant find build player content?
ive be building the asset groups?
im pretty sure ive been doing that
clean build then a new default build
could the default build script be broken and not building anything outside of the default group?
should i light the addressables on fire?
You will feel better if you do
seen