#archived-code-advanced
1 messages ยท Page 148 of 1
Ok uyep see - assigning horizontal_move and vertical_move from Input.GetAxisRaw
Why would you delete that part?
Just leave it there
ok
Add your animation stuff separately
so a new script?
@compact ingot ok, now i have these
I removed GL.Clear and using WaitForEndOfFrame instead of return null
it no longer works when i press Play in editor now. it displays these straight away
How did you conclude that?
- Get your input from GetAxisRaw and store it in your variables (you have this part already)
- Use those variables both to move the player, and as parameters for the animator
- Please post questions like this in the appropriate channel.
#1 render texture and result texture you copy into should have the same size
#2 whats in line 81 now?
I got it working mostly...
Yellz yea it works. It just takes like a second for it to render on start
Which is slightly annoying
https://mystb.in/ConfigInvestorPolls.csharp Current script
you could check if image.Apply(); is the culprit, if it is, nothing you can do about it
yeah a new script
it works now
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Animation : MonoBehaviour
{
public Animator player_animator;
// Start is called before the first frame update
void Start()
{
player_animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
player_animator.SetFloat("vertical", Input.GetAxisRaw("Vertical"));
player_animator.SetFloat("horizontal", Input.GetAxisRaw("Horizontal"));
}
}```
@zenith ginkgo you could also try using RenderTexture.GetTemporary. supposedly that is optimized for such throwaway use cases
Where abouts?
instead of new RenderTexture() do RenderTexture.GetTemporary()
Gotcha. I'll uise it, but it didnt speed anything up
Since what i need is a temporary RT for literally 1 frame
Thank you ๐
I have a NetworkManager singleton that I'm currently managing within Unity (leveraging the Update() loop to poll for networking events), keeping it loaded between scenes and so on. I am thinking of moving it to a pure static singleton without monobehaviour functionality so I don't need to establish references to it throughout my codebase. Thoughts?
How will you poll for events?
(in fact I'm thinking of moving more and more of my codebase away from MonoBehaviours unless it's specifically graphics/sound)
Not sure yet, but thinking that I'd do it in the same way that I am on the server - waiting and synchronous events
essentially
while (true)
mysocket.SyncronizationEvent.WaitOne(1000);
mysocket.HandleNetworkEvent();
I'm not sure if that's gonna be compatible with unity, actually
You'll need to run this on a background thread then, and you'lll need a way to marshall data back into the main thread.
all of which is a good idea
Yeah, I mean, I'd have to basically cleave off the network manager as a c# singleton and then give it access back to unity via other methods
yep
(or honestly, move all of the "engine" game logic and so on just into pure C# and just keep the display logic in unity)
it's pretty close to how my codebase is organized now, but my engine objects are still monobehaviour (and probably don't really need to be)
Aight. This is gonna be a big refactor but I think.. for the best. rolls up sleeves
why not a ddol? Networking in pure c# works (threading/tpl) but it usually gives more overhead when you need to synchronize the data with main thread which you would need most likely at some point (positional updates for ex)
Well some code has to get the data into the main thread. Whether that's Sharping's code or some library code.
That overhead can't be avoided if you want to use that data to render something in Unity's main loop
Library code which uses networking cannot be avoided because most of them do use threading to keep the logics intact. Polling networking events using a new thread might not be always a good solution.
I have projects which have threaded network polling, and also some which have polling in main thread. I use polling in a bg thread only when I'm very certain that majority of my data doesn't need to be synchronized with Unity's gameobjects (voip)
My game has limited updates that need any sync or client side prediction reconciliation (turn based strategy). I'm not opposed to a ddol approach but am increasing amount of code is unrelated to unity and I might even need to reuse it in non-unity clients (was toying with the idea of load testing or computer player agents without rendering needs)
Currently there's no logical difference in my game loop and a worker thread doing networking.. most of these managers have all the unity game loop methods commented out entirely (well, not even there, but you know what I mean)
I'm just feeling like the MB overhead might not be a cost I need to pay.. even the singleton framework approach requires some effort (ie, findobjectoftype and some thought on load order)
I would expect domain reload to be killing them automatically, unless you have it disabled?
The proper architectural answer is "all your asyncs should be using cancellation tokens that shut them down when the objects they depend on are destroyed", but I understand that that can be tough to add in after the fact.
Is it possible to play a blend tree from code or make my own via code?
Should work like other states. You can't edit the state machine structure at runtime.
If I do characterAnimator.Play("Move",0)
where "Move" is the name of the Blend Tree it will give an error saying that it could not be found during runtime.
Do other states work?
Does your case necessitate use of Play over parameters and transitions?
Other states do work. I would prefer not to have to deal with making that web of animations.
You can do a trigger transition from "any" which is pretty similar.
That still ends up using parameters that are just checking the state no? I have a state machine for my character and I want that to handle playing animations. But just struggling with getting a blended animation for movement
I don't know what you mean. It's just a normal trigger transition.
You'll need a parameter as the input for the blend tree anyway
Could I get some help on figuring out how to approach this camera script to take both controller input, and mouse input? I'm sort of on a time crunch, and have to adapt what I have.
Horizontal2 and Vertical2 are both added inputs in the original Unity input manager. The Mouse X and Mouse Y are still there and intact.
My controller input from the joystick is working beautifully, so I'm trying to keep that as intact as possible.
void Update()
{
//savedVec = Smash.savedVector;
currentX += Input.GetAxis("Horizontal2") * sensX;
currentY += Input.GetAxis("Vertical2") * -(sensY);
}
private void LateUpdate()
{
if (lookAt != null)
{
Vector3 dir = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY + 12, currentX + initialOffset, 0);
transform.position = lookAt.position + rotation * dir;
transform.LookAt(lookAt);
}
}```
You'd just add the mouse input to the current X/Y. If it doesn't move it's gonna be 0, so it won't contribute to the rotation. Otherwise both inputs contribute to the rotation.
I genuinely thought it would break something, but by golly that did the trick, and there's no odd behavior. Thank you
Although, I do have a follow-up question.
A user is claiming to be getting random camera input while playing, but I genuinely have no idea what could be causing it.
I have tested the game on multiple devices, and both PS4 and Xbox controller inputs.
I can't seem to run into any issue. This is the code for the camera controller input above.
The Horizontal2 and Vertical2 inputs take in the Joystick Axis assigned to the right stick. There's no alt buttons
Also, I just did a debug, and the only input detected is my current Xbox controller, so this has to somehow be code related.
Maybe his controller is broken and is submitting random inputs
Welp, sadly my first review for my first self published Steam game is negative, because of a possible broken controller haha.
If anyone comes up with anything please let me know.
The only way to know is to ask the use for more info
If you're in close contact with that specific user, maybe you could give him a debug build that would output the necessary data into a log file and they'll send it to you.
i made an implicit contructor that accepts Action as single argument, however i can not supply a method directly without casting to Action first
Binding = Method; //method group error
Binding = (Action)Method; // works
is there any way around that?
ideally i wouldnt want to cast
Should be working normally, unless your method has a different signature than Action
ie. no return value, parameterless
nope doesnt
i guess the overload resolution for delegates happens on compiler level
special treatment
Compiles:
Action Binding = Method;
void Method() { }
Binding is not an action
ok sorry
Binding binding = Method;
where Binding is a class with implicit constructor
public static implicit operator Binding<T>(Action onEvent)
{
return new Binding<T>(onEvent);
}
How is the compiler supposed to infer what T is?
Looks like a recursion to me
from the declaration
i skipped in the example
the declaration of what? T can be anything given your code so far
the declaration of the variable to which it is being assigned
Of the class probably, might be class Binding<T>
Binding<SomeParam> binding = ...
Yeah it is
Yep, getting the error too
Forcefully casting to Action makes it compile
Cannot overcome that, as the root of the error is deeply integrated in the language. IL-level
seems so
hello
I wanna get data from my desktop to an app via wifi or a usb cable
the app being a standard apk
the problem is
I wanna send data like windows, say, spotify, any game
and I don't know how to display them there
Wdym by "send data like windows"
sorry uhh
I mean like
I have an oculus quest 2
and I wanna have an app on the desktop and one on the oculus
the desktop one sends data to the oculus one via a usb or wifi
or just
I need to get data onto an android app from the desktop
I don't know how else to explain it-
like, username, avatar etc.
apps open
and so on
Could serve up the data from a RESTful API running on your desktop over HTTP
USB would be different, lower level
since there are only two devices, a socket would be your best bet. you can create local socket for a duplex transport easily and would have the fastest transfer rate compares to other options.
For USB, you need to use adb in your pc to portforward to the needed port and connect your pc to localhost at that port hosted by Android. USB still has few limitations especially in Android (need authorized adb, developer mode, etc)
so, I learnt how to make my own RESTful API
and I have no idea how to actually implement it to send data to my android from my pc
@sly grove
now you have your Android call endpoints on your API to get the information it needs
If you've made a RESTful API (amazing you learned how to do that in like an hour), the whole point of that API is that clients can make HTTP requests to it to transfer data.
so, your Android app needs to just make HTTP requests to your API
I think I get it-
omg is it really that easy-
but uhh
to transfer data, I'm gonna need to have the app both on windows and android
so, I can use #if and #endif statements to check for that, right?
which app
No I get that.
and uhh
Which side is Unity though
I need it to be the same
both-
both run natively-
that's my plan
so
it would work, right?
sure, but you're going to have to take special care
if your API server is also your Unity game
then you're going to have to know how to deal with multiple threads on the server
thank you btw~!!
ah, I see
I have my project split into its own assemblies. I need to access an imported projects namespace but it does not have an assembly definition to reference. How would I access the namespace from within my own assembly?
create an assembly reference file in the folder
just like an assembly
make a reference one
and use that
@odd ridge
you would have to give it an asmdef
I've done this before with assets from tjhe asset store that didn't have asmdefs - just throw an asmdef in the root of the scripts folder for the asset
Is this the correct way to make sure no other script can edit a public variable?
public bool playerIsGrounded { get { return isGrounded; } private set { ; } }
private bool isGrounded;
the private set is risky because if you accidentally do playerIsGrounded = ... inside the class, it will silently do nothing
you can just omit a set altogether
I don't expect complications within this script alone.
Is there another approach you would recommend?
it's good practice to avoid setting traps for yourself
I agree. I just don't understand how get-set works yet.
if I understood you correctly, I can just
public bool playerIsGrounded { get { return isGrounded; } }
Alright, great. Thank you. I'll see if I can understand this better over time.
hm, alright
public bool playerIsGrounded { get { return isGrounded; } private set { isGrounded = value; } }
private bool isGrounded;
this is what you're looking for^
ah, so that's the correct syntax
but how is that different from the solution above?
what's the point if it makes it mutable outside the class?
oh, misread
nevermind
The script is a ground check, and I want it to be the only script to set the player's grounded state
with this, you can call both playerIsGrounded and isGrounded anywhere in your code and both will read the same value.
additionally you can serialize isGrounded or view it in Debug window if you're interested
https://www.w3schools.com/cs/cs_properties.php
Reading on in the third* example, the site states that it does exactly the same, just with much less code, and no need for a variable in-between.
Do you agree that this can be sufficient in every way?
public bool playerIsGrounded { get { return isGrounded; } private set { isGrounded = value; } }
// vs
public bool isGrounded { get; set; }
hey all im currently receiving these errors in the shader Editor and have been stuck for like 3 days. our application does use assembly references and this is my gut of the root of the error
public bool isGrounded { get; private set; } = false will be a property that can be publicly read but can only be set within the containing class. It will not be serialised. If those are the behaviours you're looking for, then it's a reasonable choice.
#archived-shaders <- have you tried this channel?
will try now
There's no point in having two properties in this case.
tjm's solution is good
Thank you for clearing that out.
I just want the main script to set the value of the public field
I assumed they were meant to be alternatives? There's a faint // vs comment in between them.
oh you're right
you can also do it with serialization like this:
[field: SerializeField]
public int TotalHealth {get; private set; }```
that will:
- Show/be settable in the inspector
- Only be settable from within the class
- Be gettable from outside the class
Is the name of an auto-implemented property's backing field actually guaranteed to be consistent between compilations, though?
awesome :)
it doesn't matter really. The actual field name is something like <k_BackingField>TotalHealth
[field: SerializeField] or can it be [SerializeField] ?
has to be [field: SerializeField]
properties are not serializable but you can put the attribute on the auto implemented backing field this way
Oh I see what you're getting at @small badge
for serialization?
Yeah, I just wasn't sure whether that name was guaranteed consistent; obviously if it changed then any data serialised under the old name would be lost. Sounds like it is, though.
Pretty sure it's consistent, yeah
good stuff
while we're at it - is there a simpler way of displaying read-only values in the inspector, without using OnDrawGUI?
I've used this for a couple years now without issue
Unfortunately not as far as I know. not in base Unity anyway
things like Odin will have that
Unity has a [ReadOnly] attribute now, I think. Possibly only in 2020 and later?
Does it? I thought it was for the job system only
Yeah, you're right, I was misremembering seeing that in code.
Yeah I got fooled by that too ๐
Thanks a lot for the help, guys o/
Now I know 5 ways to do the same thing :D
well, almost the same things
@hallow cove @sly grove Thank you!
Hey, 2 things:
- For visualizing an audioloop, I want to create dynamic 3D shapes that move with the music. Is a good solution to this to create e.g 64 cubes that I animate based on the music?
Like so
Cool! So are you planning on assigning different cubes to different frequencies, then adjusting their Y scale based on dB? That seems like it could totally work, although I don't know how to read frequency/dB in Unity without doing some research
Something like that, yeah!
Oh also, here's the code for that I made at least:
AudioSource src = GetComponent<AudioSource>();
float[] samples = new float[src.clip.samples * src.clip.channels];
src.clip.GetData(samples, 0);
Debug.Log("Sample length = " + samples.Length);
int squares = 32;
int sampleSpace = samples.Length / squares;
float[] visSamples = new float[squares];
for (int i = 0; i < visSamples.Length; ++i)
{
Debug.Log("Getting data from point nr: " + (i * sampleSpace));
visSamples[i] = samples[i*sampleSpace];
}
Anyhow, is it too straining on the PC to create that many squares? I'm also not quite sure how to time the "sample playhead" together with the audio bars.
Better would be to use a custom shader, GL lines, VFX Graph or a particle effect.
Interesting, got any places to check out?
All in all, I'm working towards two things here that I'm not sure how I'll do:
- Creating a sequencer in Unity, which I am then able to match up to a loop. E.g sequence 4 kicks, when the kick plays it will animate something.
- Creating the specific real-time audio visualization, either with real-time 3D objects or what Praetor mentioned.
Furthermore, as I want to create the visualizations during runtime, is there a way to extract several clips into one audio spectrum data file?
Np~!!
Does anyone know what a CodeGen assembly is or how to decipher this error to go about resolving it? In Unity 2020.3.22f1
edit: I found the folder its referencing, but i honestly don't know where to go from here
Assembly 'Unity.Properties.Codegen' is a CodeGen assembly and cannot be Auto Referenced (Packages/com.unity.properties/Unity.Properties.Codegen/Unity.Properties.Codegen.asmdef)
this is a nice series on audio visualisation in unity
https://youtube.com/playlist?list=PL3POsQzaCw53p2tA6AWf7_AWgplskR0Vo
Anyone here a matrix math whiz?
Just ask the question
I have a simple question that I asked about yesterday
I have this RESTful API I made and I still don't really understand what the GET and POST do
like, let's say the api runs on my pc, and I wanna get the name of the pc user
You made the api?๐ค
I made whatever this is
it's gonna run on my pc and I need it to send the username of the windows user to an android
do I need to use the post function at all?
or just
get
In APIs there isn't much difference, other than semantics. In theory and roughly speaking GET is for retrieving data and POST is for sending data.
You need Post to send something to the server. You need get to get something from a server
Typically you'd GET user info and POST to change/create user info
If you just want to retrieve the user then you only need the GET
also
I saw someone use a /:id at the end
I would like to know what that's all about
It's for specifying which user's data they want
Do you have more than one user?
Do you want the name on the windows profile? Or the profile or whatever passes as a user in your game?
yup
and yes, I do want the windows username
and the avatar
I mean if you just want the Windows username of the person playing the game, then you don't have more than one user
but this is more to send data from one pc and stuff
or you don't need to specify the ID because you don't need it
they all use port 8080
if I request something on the api
I need it to return data from a paired pc or something
this is a pain I don't know how to use javascript----
I'm not sure I understand what your setup is
so
I use node js to start a socket on port 8080
and then I use GET API requests in a unity app
and then here I need it to return the username
however
I need a way to tell the unity app what pc it corresponds to
does that make sense...??
I don't know I just learn how to write REALful APIs yesterday-
Is the Node server running on the same computer as the Unity app?
no
the android app needs to get data from the pc so that's why
I saw apps using a pairing method
uh, you have an android app, a node server, a unity app, and a pc..?
where it gives you a number and asks you if it's correct
Ok so the Node server can't get the Windows username of the Unity app
the unity and android app are the same
it gets the username of the computer where the server is running
when I say the unity app, I mean the one on android
and I need an api on the pc
so the android can GET data from it
aka, the unity app
not to mention that Android phones don't run on Windows
dsfuybvsyuvdf
yesss
so rn
I'm extremely rusty when it comes to this, but from memory of web development, I am confident that you always use GET unless Custom User Input is required, for security purposes.
I have to write the API in Javascript
and have it send data when the unity app requests it
so
I don't know how to get the name and avatar of the windows user
I do also need to have the app open apps and stuff
but I need a way to tell the unity app what pc to connect to
that's my problem atm
Name and avatar of the user who is running the server?
I need the api to send the username of the user and their microsoft pfp
to the unity app
I would do it like this for the username
pretty simple
Isn't this running ON android..?
wait wdym
Again, the username of the person who is using the Unity app or the computer which is running the Node server? Which one?
I have an android app made in unity, the app requests data from an api running on the windows machine using GET requests
computer
computer which is running the node server
Ok, great, finally
Yeah, I only asked 5 times, sorry
Then you don't need the /:id part because you don't have multiple users, you have only one user, the one that's running the server
but what if I have multiple users on the same network
if I have two android apps getting and posting data to the api, then they both control the same system
don't they?
The server is running only under one user
I mean like, if I have two pcs, and two android apps
how does one android phone know which pc to use
I need to have them kinda "pair"
They would have different addresses
uhhhh
how do I do that then-
atm I have one address and it's localhost:8080/vrtop
how do I make multiple addresses and how do I get them to show in the app
You need the public IP of the computer, like 11.22.33.44, and then access with 11.22.33.44:8080/vrtop
Also note that setting up a server on your own computer isn't a stable solution, for something permanent you'd need an actual server
so
the android app is actually for the oculus
and I need to access data from ones personal computer
so, how can I get a list of all the pcs on the network that are running the api
if I can get that, I can get their ip addresses and "pair" them
You can't
uhhhhhhhh
so then, how could I have the user select which pc to connect two from their oculus quest
You'd have to hardcode the IP addresses into the Unity app
uhhhhhhh-
I could maybe make it so the app shows them their unique ip address
and have them input it in the quest
right?
I don't know how Quest works, but why would the user have to input it manually?
it's literally android
Or is Quest separate from the app?
just different input
I need to have the quest, aka, a literally android device, know what pc it has to receive data from
if I have two pcs running a node js server with the same address, and I request data from that address, it's gonna return both of them at the same time
so it wouldn't work
I know a lot of apps just make you put in your ip address
and connect your phone and pc that way
usually for wireless camera feed and stuff
If that works for you then sure
now, I need to somehow make the api get data from the pc, but I have no idea how to use javascript
is there any way I can do that with two unity apps instead of one unity app and one js script???
like
an api running on another unity app
I am very tired please excuse my dumbness
basically, I wanna use unity to get data from the pc, and not javascript
and apparently I can make a unity app on the pc and have it serve as the api
Again, if that works for you then go for it
would it be possible for me to change the serialized CAB dirs/CAB ids of an uncompressed assetbundle? my attempt at doing so utterly failed because of it refusing to load related bundle resources
the end result looked something like this
now I realize I should've probably asked this before making an api but uhh
I need to send stuff like
the whole window from a windows pc
let's say I open spotify
I need to get the window to be displayed on the android-
so umm
I just realized that I have no idea how fast restful apis actually are
can somebody tell me how fast they are?
As fast as the outgoing internet connection
but streaming content from other software is ... well, let's just say I wouldn't start building stuff like that and I've done REST APIs for 10+ years
REST APIs are just HTTP requests. They shouldn't be used for streaming video.
there's no problem streaming video from a Node server but getting the video in the first place and everything else around it is a whole another ballpark
so
what do I use then
I somehow need to get a windows window to show up on the android screen
like
I don't need a full screen share
I just need the apps to show up as windows like they would in windows
but on an android
either via cable or wireless
let's say
I wanna make a custom desktop skin in unity
and I wanna send that data from the pc to and android phone
I wanna have the window show up like it would on pc
@hallow cove I'll be honest, if you have to ask and you can't find solutions online yourself, this is probably beyond your capabilities. Like @devout hare hinted at, this is not a simple problem with a simple solution.
I just don't know what tools to use
I can code the project
I just don't know what tools I would use
it's definitely out of my capabilities
but that's the whole purpose of this project
There are at least 4 steps here. 1. Find some way to record apps on Windows. 2. Encode that into a compressed video stream. 3. Stream that either over the network or over USB. 4. Decode the video stream on the Android client.
well----------
Maybe start one step at a time. Just figure out a way to display an app window in the Unity editor. Ignore the streaming part for now.
I was thinking the same, I thought maybe I could get some gpu data that renders the windows, but then I wouldn't be able to interact with them most likely
that's the biggest challenge of this whole thing
I don't think so. I think there are Unity assets that do that.
This can definitely be done with importing win32 specific functions into C# that allow you to capture a window. After you've done that you could craft a workspace similiar to ConsoleWorkspace that will allow you to render the results. Hooking back up input support to control the mouse pointer will require a little work, but is doable, too, also with win32 calls. I hope that points you in the right direction.
someone asked the exact thing I need
(assuming you want to also have a Unity client on Windows)
yes
@hallow cove This looks like it will take you 75% there
https://github.com/hecomi/UnityRemoteDesktopDuplication
If you're okay with nvidia GPU requirement on the Windows client
It doesn't say this works on Android, but I think it streams data from one Unity client to another
It uses this to get the desktop feed in Unity
https://github.com/hecomi/uDesktopDuplication
if this project works out I'm planning on pushing it heavily and making it open source so idk-
You can maybe find another cross-platform video encoder library
No license on this though...
wdym?
It doesn't specify a license, which tells you how you may use it in your own projects.
I see-
Oh nevermind, it's in the readme. MIT license
how to fix
Posting in the advanced channel, what a rush
I'm refactoring parts of my project to add some multithreading and I'm looking for the most efficient possible way to throw an exception if you try to call certain functions from the wrong thread (or thread type). I was thinking of turning the relevant functions into thread-local delegates, and redirect to an error function on some threads, but I was wondering if there maybe was a built-in language feature/attribute that already does that (select different code path for a given method depending on thread). The key is not having to change existing calls, and also avoiding adding conditionals inside or outside the functions as they're used in some tight loops.
oh making me mad reasding this
I wouldnโt even use Unity for this, just a lightweight Android Java app and a Windows .NET app with a web socket.
But if you really needed it in Unity, thatโs fine too. Just adds a layer between the parts.
I know how to use Unity well, so, I have more to gain by using it
Iโd argue you have less to gain by using it, if you already know it well, as you wonโt learn as much
But, either way, Iโd use a web socket and send a compressed image
Basically on Windows desktop, use this to access the base system. This is just a transparency example, but would probably work with get pixels now.
Then submit it to Android using something like this:
https://gist.github.com/danielbierwirth/0636650b005834204cb19ef5ae6ccedb
And pack the data using GZipStream and the png/jpg in a byte array
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
no u dony cause u r alt account
You are talking to yourself mate
yes u r talking u r self
my dearest frnd
life saving vegetaion tool
Who are you talking to. Nobody here is having a conversation with you. ๐ค
maybe it's literally an advanced code
Iโm not so sure in the advanced part
Does anyone know how to convert a unity URP shader to the new 2D renderer? Google couldn't help me so far. It works perfectly in URP forward renderer but once I switch to 2D renderer it breaks. here is a small video showcasing the problem.
and the shader looks like this
I'm building a reference database for all possible effects for abilities in my game. I am tying them to an enum so it is easy to select from a field in a scriptable object. How would you guys go about cleaning this up or making it more manageable?
I think it's much tidier to use normal methods rather than anonymous ones. And this may be a very rare case where i'd use a delegate instead of an action to define the method signature, just to tidy up that declaration
Alrighty. Thanks.
no worries! Example
using System.Collections.Generic;
public enum GameEffect
{
healValue,
healPercent,
addAbilityPointsTrait
}
public class Character { }
public static class DB_Effect
{
public delegate void GameEffectMethod(float value, Character source, Character target, bool isRemoveEffect);
public static Dictionary<GameEffect, GameEffectMethod> EffectMethods = new Dictionary<GameEffect, GameEffectMethod>{
{ GameEffect.healValue, HealMethod },
{ GameEffect.healPercent, HealPercent },
{ GameEffect.addAbilityPointsTrait, AddAbilityPointsTrait }
};
public static void HealMethod(float value, Character source, Character target, bool isRemoveEffect)
{
}
public static void HealPercent(float value, Character source, Character target, bool isRemoveEffect)
{
}
public static void AddAbilityPointsTrait(float value, Character source, Character target, bool isRemoveEffect)
{
}
}
That does look much better. Thank you. ๐
I have an assembly that has "autoReference" set as true by default, but causes an error stating that because it is CodeGen assembly, cannot be written as "true". So i changed it to false and get this error instead now
(0,0): error System.IO.FileNotFoundException:
{
"name": "Unity.Properties.Codegen",
"references": [
"Unity.Properties"
],
"optionalUnityReferences": [],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": false,
"defineConstraints": []
}
It looks like now it cant be found if it's set to false?
Removing the assembly entirely causes a wall of errors, is there a way to rewrite this assembly to avoid either option?
To test options I commented out "autoReference" line, but then the original error returns
Assembly 'Unity.Properties.Codegen' is a CodeGen assembly and cannot be Auto Referenced (Packages/com.unity.properties/Unity.Properties.Codegen/Unity.Properties.Codegen.asmdef)
If it's known it cant be autoReferenced, I'm not sure why it was written this way. Or because maybe in Unity 2018.3 it could be but not in 2020.3? Any help is super appreciated
bruh why u pingt me! u pinged the all mighty busy man
you are off your rockers
You have to reference it in your assemblies if you want to access it. You'll have to add an assembly definition to your code if you don't already have one.
I'm not sure how to reference it in the assembly, i mean i see it in inspector and can compare it to how its written in visual studio, otherwise im not sure how to do that
I was messing around with it to see visual changes but i noticed when i make a change it will apply them, but then when i go back to make another edit it will automatically revert to its default settings
That's probably because you can't modify installed packages.
Have you checked if there's an update for this particular package in the package manager?
Not since 2018
This is the manifest for the folder of Unity.Properties.CodeGen, no updates for this since the date of 2018 written there
Since it's been so long since it's been updated and it's still in preview, it leads me to believe it simply isn't supported anymore. What Unity version are you using with it?
Originally 2018.3.8, now its in 2020.3.22
Was it working with 2018.3.8 and stopped working after the upgrade?
yupp, i mean i know its a drastic upgrade, but the other wall of errors was fixable, except this final one
Well, whatever the fix is, you're going to have to find it yourself because it looks like Unity has stopped supporting this package.
CodeGen stuff in Unity packages have changed a bit in other packages since 2018, so however this package is doing it might not be supported by Unity 2020.
Even if you fix the reference and compile time errors, there's no guarantee it will work the same as before
Would you be able to tell me what you know about CodeGen in particular?
@muted widget Wait, I found a newer version of the package here. Last update 2020.
https://docs.unity3d.com/Packages/com.unity.properties@1.1/manual/index.html
Do you not see this version available in the Package Manager?
It won't always show as if an update is available, you have to expand the list of versions and pick the latest one yourself
When i click on "show in package manager" it opens package manager but doesnt it show it to me
It opens and just highlights the first thing on the list
(everything is as it was from 2018, even the ancient version of HDRP because thats even on version 10 now)
You have to install it manually, confusingly through the "Add package from git URL..." option
and put in the full name of the package as the URL: com.unity.properties
That was the next mission, ive seen if its not available, github is always the next option
This isn't actually installing it from Git, this is just how you manually install hidden Unity packages in 2020.3
In 2021, they've separated it into its own menu item so it's less hidden and confusing
Ohhh alright
Ah okay, that haha okay yes that did fix it, it triggered the install and then another wall of errors popped up but it was good because that was then fixed. I realize we get sent back to the normal errors we've gotten before with moving from 2018 to 2020 with references to Boo language which was deprecated in 2017
I see though, before when we've made attempts to make this leap into the newer engine for some reason we never came across the CodeGen/Unity.Properties error (would that be because of it being so old or in preview that its not guaranteed to always be problematic?), so far Boo not being in 2020 is the only issue with reference to TestUtil.cs and ABModelTests.cs
Greetings to anyone down to read this! I really didn't want to do this, but this is already my last resort. The line in question was using UnityEngine.InputSystem; and the error is:
The type or namespace name 'InputSystem' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?) [Assembly-CSharp]
I'm currently on Unity 2021.2.2f1, and this issue just suddenly popped out into existence. And please know that i know this. i know what i should do to get it fixed. But here's the thing, as you can see on attached image:
- I have Visual Studio Code Editor package installed in my Unity project,
- I also have Input System package installed,
- Configured in Preferences to generate .csproj files based on packages I have, and
- OmniSharp found it, successfully loaded it, and added it.
Omnisharp still fails to find UnityEngine.UI and UnityEngine.InputSystem.
No errors in Unity console. I did the following stuff which me and my friends thought would fix the problem:
- Did stuff mentioned in https://code.visualstudio.com/docs/other/unity
- Downgraded, and Updated Visual Studio Code Editor package latest, 1.2.4
- Manually deleted all .csproj files and regenerated them
- Right click > Reimport All (because this deletes and recreates cache data)
- Manually deleted "library" folder
- Attempted to update VSCode and the C# Omnisharp extension (both up to date anyway)
- Installed Mono (which actually fixed my Intellisense/Omnisharp issue before in 2020.1b)
I also made a new, clean project with the same stuff installed, and the issue persists. And apparently, It's not only InputSystem that's affected. UnityEngine.UI, UnityEngine.TMPro, and UnityEngine.Rendering as well.
Any clue on what I should do now? Feel free to ping me anytime if you're down to help...
In my experience VS Code integration 1.2.4 doesn't work; references to code in packages aren't recognised, which sounds like exactly the problem you're having. The only thing that fixed it for me was downgrading to 1.2.3.
(I read the rest of the message)
(By manually editing manifest.json, since PackageManager doesn't offer an option to downgrade.)
Is that method any different from this one though 
oh shit i pinged, mb
(And obviously then you'll need to regenerate solutions, yada yada yada.)
I haven't actually tried that option yet; if it lets you specify a version number it should work fine.
It does; I've done this before where i even downgraded multiple times down to latest 1.1.x and 1.1.1 which, i have to mention: worked flawlessly on VSCode in Unity 2020.x
but here in 2021.2.2, even downgrading doesn't fix it :(
I was thinking, is there anything within Unity or Unity packages that needs Visual Studio Build Tools 2017? I may have updated to BT 2019 last week, but the thing is that this problem already existed 2 and a half weeks ago
Then I don't think I can help, sadly; even going over the changes from 1.2.3 to 1.2.4 with a fine-toothed comb I wasn't able to conclusively figure out what was causing the problem I had, so I can't really say how it might be affecting you. All I can offer is a data point that I got it working with Unity 2021.1, VS Code integration 1.2.3 and VS Code 1.62.2.
The only difference we have in versions would be Unity itself... I'll just downgrade to 2021.1 for the meantime

I feel like I'd be surprised if it was a build tools issue? Failing to recognise dependencies seems like it would always be a csproj/solution generation issue, and I don't think anything in that process is reliant on the build tools. But I'm not an expert on the VS code solution pipeline so I can't say for sure.
I was also hesitant with it being a problem with VS/VS BT since I also tried using VS 2019 as my external editor and it works flawlessly, with all that references and omnisharp and intellisense
but having chrome, vs2019, and unity at the same time feels too clunky for me so i wanted to fix vscode
either way, thanks @small badge! really appreciate your help :))
also you @sage radish ๐
In case it helps, I believe this bug report (and associated pull request) was the problem I was having with 1.2.4: https://github.com/Unity-Technologies/com.unity.ide.vscode/issues/4
Just in case it suggests other things to look at; for example, since the issue seems to be path related maybe check whether either the unity project or the package cache are located in a path containing uncommon characters.
Oooh, that might just be the issue i'm having? I have assets from Asset Store, like Shapes by Freya and it's not throwing any kind of issue and Omnisharp acknowledges the package and it's scripts/references
Stuff's inside Library\PackageCache\com.unity.inputsystem@1.1.1\... while the .csproj files lead to Packages\com.unity.inputsystem\... which is completely different, and that path doesnt exist because there's nothing in Packages folder other than two json files
EDIT: 1.2.3 regenerates the .csproj files with the right path, but didn't replace the .csproj files; Downgrade works but I also had to delete all of the .csproj files from v1.2.4 so that v1.2.3 can generate freely
That was an oversight from me, my bad; Thanks again!
Does PlayerPrefs immediately write to disk or does it store everything in some location in the program memory and write to disk when the application quits?
Perhaps you want to reset the scene's contents. Reloading in an additive context would mean to first unload it and then load it.
If it's a reset you could write custom logic for that.
They go to the Registry.
Computer\HKEY_CURRENT_USER\Software\[CompanyName]\ProductName
Oh i didn't see the last part
The application saves quite a lot upon quitting, such as last resolution used, etc.
Here's some of them:
Well it's not like Unity reveals how it implements PlayerPrefs since it's not written in C#
These look like EditorPrefs entries
if you want control, write your own.
welp that's the thing really
it'll probably not be of much use unless I am making a much bigger game
i'd not expect anything in unity that deals with the runtime platform (i.e. the OS) to be immediate
it almost certainly wont be immediate
As a matter of opinion, me neither. It is much more sensible to hold stuff in memory, then write it to disk when the app exits normally or terminates (unless it's small enough or maybe crucial to store immediately?).
but whether it is deferred until application exit... you can just test that
depends on what it is, that doesn't hold as general principle...
It'd be awesome if it happens interstitially
at that point you're probably better off controlling exactly when it happens and create a custom save system
True, true.
Hey, I have a math question
So here's my problem: I have a camera, and I have a formula that takes in position between {-0.5,-0.5} and {0.5, 0.5} and return a direction from the camera to a point on a picture that's 1 unit of distance away from the camera
{-0.5,-0.5} corresponding to the bottom left corner of the picture
And {0.5,0.5} the top right
The thing is I can't use camera.main.screentoworld, it just doesn't do what I want and is too dependent on the screen size
I need something that would behave the exact same on all computers
For my formulas, I'm using x * Mathf.Tan(fov.x / 2 * Mathf.Deg2Rad) * 2, y * Mathf.Tan(fov.x / 2 * Mathf.Deg2Rad) * 2
Fov is a vector with both the horizontal and vertical field of view of the camera that took the picture.
I'm not getting the exact expected size, though. Are my formulas wrong?
Let me put it in a different way. How would you get the size of the base of an isosceles triangle, given the opposite angle and the height of the triangle?
Is it indeed tan (angle / 2) * height * 2 ?
dunno about the maths, but have experienced much irritation with the fov being odd in Unity.
Yeah, but it looks like the fov I'm given is correct
I'm not given the fov of the camera of a scene, I'm given a photo and the fov of the camera that took the photo. From a different project.
is the fov value coming from one of Unity's cameras?
if you think you've got the maths right (I have no idea about this), then start figuring out ways to examine the accuracy of fov. It is weird, in Unity, for me, someone that thinks in terms of physical cameras. And is made much weirder by interactions with the options of aspect ratios you can and can't control (as these can impact the pixel aspect ratio, too), and the sensor size/shape simulations, and the lens simulations. Don't trust the fov values, first and foremost.
So I just checked the code, the fov I get is not a camera.fov, it's computed in a completely independent way.
But it is originating from an unity camera
Ok, you can go hunt down how they presume to calculate FOV, and then figure out how that pertains to each and every device variation and aspect ratio you target, or... try thinking differently about how to achieve your desired insight by using ray casting. I'd go with ray casting!!!
All of this is done to get a direction vector to give to a ray cast... ^^"
I understand, really, I do. Think the other way around, world to view origin, etc, then back out again. Sorry... the fov thingy in Unity has driven me mad, before, so I somewhat know what you're going through.
Hahaha alright. I'm reviewing the code that compute the fov to see if I get mistakes from there (between us the dude that wrote that code has written many scripts of... questionable quality)
best of luck! Also, as a general rule of thumb, if there's a weird, counter-intuitive, non industry standard manner in which Unity could do something, and then further ways they could make it odd - that's the way they've chosen to do it. This is so consistently the case, across so much of Unity, that it's best to presume this is the source of problems whenever something misbehaves, to save yourself time and sanity querying your own code and methodologies.
Hello, I got a non urgent question. I recently figured out I could use a combination of the [RequireComponent()] attribute and a [SerializeField,HideInInspector] decorated field of the same type that I assign in OnValidate() to get serialized references to other behaviour on a gameObject.
I like it for several reasons, it keeps the inspector clean, prevents designer from forgetting to set or missusing the field and garantees that the field is populated when an Awake() or Start() methods is called, regardless of execution order.
What am I missing here ? It seems like a fairly obvious pattern in retrospect but I've never seen it used. Is there a edge case I'm missing where these reference will be null ? (Excluding adding the component at runtime using AddComponent)
Another loophole besides AddComponent is an instance of the component that was created in a scene or prefab before those attributes were added. If the prefab or scene is not opened again afterwards, the component may not be present and the serialized field may not be populated
But it seems pretty solid
It does require adding 3 attributes across a field and the class itself, as well as writing an OnValidate() method.
So that complexity may explain why you haven't seen it
The interaction with prefabs does sound dangerous, so I'll hold off peppering production code with it, thanks for pointing it out. I don't mind the complexity too much, as it's much simpler than even the most basic custom inspector.
Hello. Can someone help me with one thing?
I'm making a game in the style of Timberman.
I created one script. In this script in the update method, I would like it to change the position in one of the axes by 200 units within 0.2s with each click. (I click, then it change position and I can click again)
It is an object that can move endlessly and moves in relation to itself.
I'd use a Coroutine for that, lerping the object position over 0.2s (you can use "yield return null" to halt execution of the coroutine until next frame). Remember to have some kind of check to prevent that Coroutine to be started before the previous one is finished.
Okey I'll try that thx
how to use hdrp for 2d platformer game?! help!!!
how to use post processing for 2D platformer game?! help!!!
This is... not a good question
how to ask good question?! help!!!
how to open link on discord on windows 12
12!?
apparently I missed the humor bus this morning .. my fault, carry on
sorry i was bored while installing unity 2021.2 and vs 2022
are there any differences between vs 2019 and 2022?
no they just wanted a bigger number
xD
the vr template has oculus sdk and xr. is that just for multiplatform compatibility or is there a reason to use both?
omg... microsoft is bored...
64 bit, perf improvements, hot reload, intellicode, icons,
a couple small things here and there, really
biggest news is dotnet 6 and c# 10
#497872469911404564 if you want to discuss unrelated stuff.
my b
So I'm starting a new side project, an Idle game, and before I roll my own "big number" class (essentially a float and exponent), is there something that's already been done here? Should I just use System.Numerics.BigInteger?
(and maybe BigInteger isn't necessary since I don't need that precision)
Actually, it's definitely not the right approach since I don't want to bloat the network/storage space with this data structure that looks like it gets as large as needed, to hold the precision
Hi! I've been working on procedural generation and I've gotten to here (see image).
How can I make more islands and make it look less like a mess.
private void Start()
{
GenerateMap();
}
private void LateUpdate()
{
if (Input.GetKeyDown(KeyCode.Space))
GenerateMap();
}
private void GenerateMap()
{
map = new int[width, height];
decoMap = new int[width, height];
print(map.ToString());
RandomFillMap();
for (int i = 0; i < smoothTimes; i++)
{
SmoothMap();
}
UpdateTilemap();
}
private void RandomFillMap()
{
if (useRandomSeed)
{
seed = UnityEngine.Random.Range(1, 1000).ToString();
}
rand = new System.Random(seed.GetHashCode());
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (x == 0 || x == width - 1 || y == 0 || y == height - 1)
{
map[x, y] = 1;
}
else
{
map[x, y] = rand.Next(0, 100) < randomFillPercent ? 1 : 0;
}
}
}
}
private void SmoothMap()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int neighbourWallTiles = GetSurroundingWallCount(x, y);
if (neighbourWallTiles > 4)
{
map[x, y] = 1;
decoMap[x, y] = 0;
} else if (neighbourWallTiles < 4)
{
map[x, y] = 0;
decoMap[x, y] = rand.Next(0, 100) < decoFillPercent ? 1 : 0;
}
}
}
}
private int GetSurroundingWallCount(int gridX, int gridY)
{
int wallCount = 0;
for (int neighbourX = gridX - 1; neighbourX <= gridX + 1; neighbourX++)
{
for (int neighbourY = gridY - 1; neighbourY <= gridY + 1; neighbourY++)
{
if (neighbourX >= 0 && neighbourX < width && neighbourY >= 0 && neighbourY < height)
{
wallCount += map[neighbourX, neighbourY];
}
else
{
wallCount++;
}
}
}
return wallCount;
}
private void UpdateTilemap()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (x == 0 || x == width - 1 || y == 0 || y == height - 1)
{
waterTileMap.SetTile(new Vector3Int(x, y, 0), waterTile);
}
if (map[x,y] == 0)
{
mainTileMap.SetTile(new Vector3Int(x, y, 0), grassTile);
} else
{
waterTileMap.SetTile(new Vector3Int(x, y, 0), waterTile);
}
if (decoMap[x, y] == 0)
{
decoTileMap.SetTile(new Vector3Int(x, y, 0), null);
}
else
{
decoTileMap.SetTile(new Vector3Int(x, y, 0), waterTile);
}
}
}
}
The "bloat" is absolutely insignificant
Google Perlin Noise
Er, not at all?
I'm using Cellular Automata
I just need to make it more islandly and not like a swamp
How large numbers are you planning to use?
The game is networked so... the clients/servers are going to be sending these values back and forth quite often
Arbitrarily large
1e900
(nonsensically large)
I don't want to send 900 bytes where 10 will do ๐
well 1e900 is obviously not 900 bytes but that's still definitely insignificant
My thought right now was to roll a BigNumber class that overrides common operators like operator+, operator- and operator* (probably don't need divide in an idle game)
So again.. the game is networked so the cost on the server of serializing/deserializing strings of 900 digits to a big number and operating on it, serializing it again into a string and then serializing that string into a byte array and encrypting it and sending it to the client for operations every few seconds for dozens/hundreds of players is .. significant enough
I mean, it's just not the right solution ๐
why not send binary
i do send binary
or did you mean sending the data of the bigint as a byte array - i could do that, that looks smaller
but again, this is a lot of work to implement something that i don't need - I don't need the precision on the value
Also, this:
Although this example appears to modify the value of the existing object, this is not the case. BigInteger objects are immutable, which means that internally, the common language runtime actually creates a new BigInteger object and assigns it a value one greater than its previous value. This new object is then returned to the caller.
Note
The other numeric types in .NET are also immutable. However, because the BigInteger type has no upper or lower bounds, its values can grow extremely large and have a measurable impact on performance.
If I'm performing operations on these on the client in every Update() .. it's going to be a resource hog
well, maybe not, i suppose, since it's just 1 or 2 instances of this
perlin noise
Again, I'm using Cellular Automata
perlin noise
:/
CA meaning what, you want to take the starting setup an use game-of-life style advancement? ie - some set of rules that determines what happens to each cell?
I mean, fundamentally what you're trying to do (and maybe what you're not understanding me/tech/mind say) is create coherent randomness
People who are pretty smart (ie, Ken Perlin) have done this and it's good, the only part you need to do is implement it, and there's hundreds+ of articles on that
essentially your RandomFillMap() should be entirely replaced with a perlin noise generator
+1
(and specifically, what you need to do is play with the output coefficient - ie, you're going to get a value from 0.0-1.0 for each tile, and you just determine if that value is a waterTile or grassTile in your setup)
your approach right now is to generate random noise and then smooth it some number of times
This is going to get you a very consistent and bland noise map
Smoothing "incoherent noise" means just a more boring/flat "incoherent noise"
So again... TLDR: scrap RandomFillMap() and implement perlin noise (and you won't even need SmoothMap after that)
it'll also be a lot faster since this is a hack:
for (int i = 0; i < smoothTimes; i++)
{
SmoothMap();
}
Is there any way to loop through hunderts of ints without lagging pc too much?
looping through trillions of ints shouldn't lag your pc
And comparing them
post your code - maybe you're doing something you aren't thinking is the problem?
also no problem
Better question is how can i cut mesh?
public static void SpeedTest()
{
int a = 1;
int b = 2;
DateTime startDT = DateTime.Now;
TimeSpan ts = DateTime.Now.Subtract(startDT);
for (int i = 0; i < 100_000_000; i++)
{
_ = (a < b);
if (i % 100_000 == 0)
Log.Debug("{i} iterations have taken {time}", i, DateTime.Now.Subtract(startDT));
}
}```
100m iterations (along with a datetime subtract and modulus operator - typically slow) in 1 sec
"cut mesh"?
yeah like you have cube and plane and you will slice the cube with the plane
I don't have experience with that but I do know that it's a ... common? complex? problem, googling should yield a lot of info on it
I seem to remember someone posted an article in the last few weeks here about novel solutions to it
ok ill try it
is there a way to create a thread that's sure to not be on the same core as the Unity Main thread, or the Unity Audio thread?
You generally can't control which core your threads run on. The CPU will schedule them as best it can
ALthough it does look like there is some kind of support for this maybe in C#? https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processthread.processoraffinity?view=net-5.0#System_Diagnostics_ProcessThread_ProcessorAffinity
I have a prefab which contains 2 MonoBehaviour scripts (script A and script B). The scriptA contains a reference to script B. When I instantiate the prefab, the Start method of the script B is called AFTER the start method of the script A. It's a problem because the script A calls script B method from its start method. Is it normal and how to solve this problem ? (I cannot use the Awake method)
do you know if each thread/core has its own registers?
they do, yes of course
A CPU could hardly do its job if it had to share registers
although with HyperThreading who knows
I think from an application perspective, you can assume yes
There is a way to set Awake/Start order, but it is heavy-handed. It would be better if you design your code so that the ordering doesn't matter.
I can do that but I have to put "Initialize" method in the script and don't use start/awake methods... not very user friendly...
anyway, thanks for your help @stable spear ๐
Generally there's cleaner ways to do initialization than have custom initialize functions, depending on what you're doing. But without seeing your code, I can't offer any specific recommendations.
Separate your initialization code into Awake and Start.
Do "self init" stuff in Awake, and code that reaches out to other objects in Start
why can't you use Awake? (just noticed that part)
There's also the OnEnable() method which will run before Start() as well
I can't use Awake because I have to separate my initialization code
as you just explained
the code in start must be in start because it's not self init
But what exactly are you initializing between scripts?
Much of the time, dependencies between scripts can be untangled and removed.
don't understand how this precludes the use of Awake. Sounds like you're doing some self init in Start that should be in Awake()
I have simplified the use case but there are others scripts that are used in script B start function
!ban 473126488728666112 scam
ddwi16#9308 was banned
I'm writing a BigNumber struct with some custom functionality, and overloading a bunch of operators. My operator + is a bit of a disaster, I think. I'm not sure how I would go about profiling this, though (in terms of memory use).. Any suggestions on starting points or google terms?
public static BigDecimal operator +(BigDecimal left, BigDecimal right)
{
if (!left.IsValid) throw new ArgumentOutOfRangeException("left", left.GetInvalidReason());
if (!right.IsValid) throw new ArgumentOutOfRangeException("right", right.GetInvalidReason());
if (left.Exponent == right.Exponent)
return new BigDecimal(left.Mantissa + right.Mantissa, left.Exponent);
//Treat left as the smaller item, swap if necessary.
if (left.Exponent > right.Exponent)
{
(left, right) = (right, left);
}
while (left.Exponent < right.Exponent)
{
left.Mantissa /= 1000;
left.Exponent += 3;
}
decimal newMantissa = right.Mantissa + left.Mantissa;
BigDecimal ret = new BigDecimal(newMantissa, right.Exponent);
ret.Adjust();
return ret;
}```
(this implementation of "big decimal" is geared towards forcing it to "multiples of 3" exponents.. so valid numbers are from 0-999 for the mantissa and 0/3/6/9... for the exponent)
you can use right.Exponent - left.Exponent to compute exactly how many times you need to shift left down. The fastest way to do it would be to operate on the 128-bit internal representation of decimal. But I'm not sure you want to get into that mess.
I tried setting a breakpoint before/after 100 million operations and snapshotting memory before/after, and it looked clean
Yeah, I definitely don't want to be touching internal representation and bitshifting unless that's the only way to optimize
there's no memory allocation, its just inefficient math-wise
well, there is memory allocation at the end with new BigDecimal
I'm just not comfortable with my skills currently to do that
only on the stack
I also have an alloc on the swap tuple operation, I think
is BigDecimal a struct?
yeah
Nothing in this code does any heap allocation except the exception raising
oh ok. then yea, no heap allocation
which is good ๐
OK.
I was literally typing "is that bad"? ๐
OK, maybe I can look at the CPU performance then.. I've actually never used the CPU profiler
Is it worth doing this now?
(left, right) = (right, left); ```
nor not really
Aye - I stole that, lemme cite the source
haha great image ๐
doesn't exactly inspire confidence
works great until it explodes due to some edge case I thought about but didn't address -- that just means it'll fit in with the rest of my code
I'm blown away, would have guess the XOR thing was the fastest but I guess not
it's just a parlor trick after all
(this article goes super deep on the performance implications of that operation, btw, which i mostly skipped over)
I was briefly considering the unsafe pointer swap and then decided against it
what's the xor thing?
(I don't have operator xor defined on this struct, fwiw)
operator^ is it? i don't think i've ever really used it.. i haven't used any sort of bitwise flag enum that I can recall, but i can't think of a common usecase for xor
X86 has an XCHG instruction for exchanging values. Not sure if the compiler can make use of that, but it is likely to be faster than a bunch of XOR.
% of samples taken at that point
I'm assuming. The fact that there are so many means that line must be taking a long time
what is IsValid ?
a property?
yeah - pretty light, actually:
private bool IsValid
{
get
{
return (IsValidMantissa && IsValidExponent);
}
}
private bool IsValidMantissa
{
get
{
if (Mantissa < 0)
return false;
return true;
}
}
private bool IsValidExponent
{
get
{
if (Exponent < 0)
return false;
if (Exponent % 3 != 0)
return false;
return true;
}
}
lol, that's light??
actually IsValidExponent has the modulus in there
i forgot about that
hm... I could theoretically get rid of it since the struct itself can't be constructed invalid-ly
(i hope)
Do you treat the fields Mantissa / Exponent as immutable after construction?
I wonder if the %3 would be faster or doing the old trick of taking the sum of digits and checking if that is divisible by 3
sort of - public get, private set, and they're only set via the operators
there's no "sum of digits" instruction that could possibly be faster
Can probably slightly improve performance by removing branching too, e.g:
private bool IsValidMantissa
{
get
{
return Mantissa >= 0;
}
}```
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
plus checking if that is divisible by three would still require %3
here's where it's at now - critiques welcome
On a much much smaller number
X86-64 operates on 32-bits or 64-bits at a time
there might be circuitry to handle 8-bit or 16-bits, not sure, but it won't be significantly faster
how can I .. uhm... dive into the hot path? I'm having trouble reading this cpu profiling thingy.. although I suppose that's not really a code/unity question and more of a tooling thing
Like - what's this mean..?
Doesn't it use an array to store all the bits, like BigInteger?
isvalidmantissa appears to be taking a big chunk of time?
does what?
Mine doesn't - internally I just store a decimal and int
Can you arrange to do the validity checks only once, upon construction?
yep, although the operator constructs as a convenience for addition with ints/decimals
see lines uh... 173ish
public static BigDecimal operator +(BigDecimal left, decimal right) => left + new BigDecimal(right);
I mean, obviously I could remove that and force the caller to ctor their own BigDecimal
ie - place the slow stuff (the modulus operator, i guess?) in the ctor and then force "consumer-sharping" to ctor and manage the right operand BigDecimal
btw, do you actually need performant code or are you just testing profiling?
I may need it - I'm anticipating that the server is going to be doing thousands-millions of these operations per second, depending on the number of connected clients
the right way to do this is probably to mimic the same representation as decimal, but with more bits. And maybe native code if needed
there's workarounds but i was hoping to put some thought in now and not have it be a refactoring headache later
what is it going to be used to represent?
If you really want to get into extreme optimization you'll need to dive into unsafe code at some point
๐
decimal's range isn't large enough for this?
no, we'll be doing the traditional genre exponential growth
the only linear progress will be the exponent
ie - generator A makes "1e1" energy per 30 sec, generator B makes "1e4" energy per 30 sec, etc... generator Z makes "1e900" energy per 30 sec
essentially nonsensically large numbers
how do you compare BigDecimal's ?
operator== overload and epsilon
public bool Equals(BigDecimal right)
{
if (!right.IsValid)
throw new ArgumentOutOfRangeException();
if (Exponent != right.Exponent)
return false;
return (Math.Abs(right.Mantissa - Mantissa) < BigDecimal.Epsilon);
}
there are multiple representations since decimal has its own exponent
(probably also will need to be optimized)
Mantissa = 100, Exponent = 0 is the same as Mantissa = 1, Exponent = 2
exponent = 2 is illegal in my struct
fine, 1000, 0 and 1, 3
1000 is also illegal ๐
why?
there is only one combination of mantissa + exponent for every number in R
it passes your checks
that's true normally, but there's two exponents here
the one internal to decimal, and the external one
it passes my checks (which I should add a check for, thanks) but should be impossible - Adjust() fixes it if the number is >= 1000
(and Adjust() is called in the ctor)
private void Adjust()
{
while (Mantissa >= 1000)
{
Mantissa /= 1000m;
Exponent += 3;
}
}
lol
i know.. i'm not sure that this struct is on the right path ๐
it works but.. man it feels stinky
I did come across this repo: https://github.com/Bakaender/IdleParts/blob/master/BigDouble.cs but this is mostly the same as mine, with slightly different behaviour
funny thing is that decimal has 22 unused bits in its internal representation
they could have easily extended the range to a huge amount
OK well I just did approx 300b allocs and 100b operator+ and it took 3.7 sec so.. i'm going to optimize later if that's not good enough
really? that's weird
where's the latest decimal source? i wanna poke in there too
https://github.com/dotnet?WT.mc_id=dotnet-35129-website here somewhere?
ah, thanks, that's what I saw too but I saw it was for framework 4.8
yeah, that's weird
Bits 0-15 (the lower word) of the flags field are
// unused and must be zero;
Wonder what for... digs into code some more
I'm assuming future expansion room for flags of some sort
Is there something that already exists for checking frustum vs box intersection? I'm surprised I havent found anything readily available so far for something that has to be common to about every 3d game out there.
(NOTE: will be used in performance-critical code)
I have a suspicion I can just use projection matrix for this but I'd rather not try to guess my way through this
@drowsy estuary https://docs.unity3d.com/ScriptReference/GeometryUtility.TestPlanesAABB.html this maybe?
Ohhh right I knew I had seen something like that before! Thanks.
Do you happen to know if this is Burst-compatible?
Nevermind, Plane uses the old Vector3 and such
Cant check the source either since it disappears off in some external C++ call.
Oh well
Anyway, thanks
how do bullet hell creators manage bullet movement? right now i have each bullet starting their respective Move() coroutines when they're spawned (which may or may not start more coroutines subsequently) but i can't imagine that being super performant for hundreds or thousands of bullets. should i be using async/await? or just updating their position/rotation through Update? or something else
Regarding frustum vs box culling:
I found this which is stated to occasionally result in "false positives" (as in; says it does intersect while it actually does not) for the sake of a more simple implementation. Is this a common compromise to make for games?
https://www.gamedev.net/forums/topic/512123-fast--and-correct-frustum---aabb-intersection/
particle system + custom shader is one possibility
As soon as you have to deal with 1000+ or even just 100+ of of something, consider DOTS/ECS if you really want to avoid performance problems later on.
Otherwise, I'd advice just letting Physics do the work for you and give each bullet a proper velocity and let the Physics engine simulate the motion for you.
either way i'm gonna have to refactor a bunch ๐ค
Well first I would start by actually figuring out how likely it is that you can get away with the Unity way. How many projectiles do you actually end up with and what sort of headroom is there?
If that fails, starting by moving projectiles to your own collections and running logic on them linearly by yourself and doing DrawMesh* calls yourself should do.
You don't need to move to ECS (and probably shouldn't until they consistently have versions available) to take advantage of some of the ECS concepts and apply them yourself
@tepid dove If rendering becomes the primary cause for performance problems, check the following things:
Plan A: Check if draw-calls for your bullets are properly batched. If not, take steps to ensure they are.
Plan B: Use Graphics.DrawMeshInstances(...). This is blazingly fast if all you want is just blast 1000 of identical objects onto the screen.
(But if physics and/or motion updates is the primary cause for performance problem, check what I said a few minutes earlier.)
async/await is something you generally don't resort to in Unity.
Primarily because a lot of Unity API is not accessible on other threads.
If you do want to go multi-thread, Jobs/DOTS/ECS is the way. However, this is really different to the MonoBehaviour approach and requires you to basically re-learn what you know about (game) programming.
yeah idk much about jobs/dots/ecs to begin with, all i know is that it's good for handling large amounts of objects but has a really different workflow? (also seemingly unfinished for an indefinite time, thanks unity)
Remember to use the profiler often! It will tell you exactly where code is slow
anyways thanks for the ideas
Super different workflow, yes.
Jobs is the best way to get some of the DOTS advantages but without having to learn so much new things.
Jobs is already fully functional and no longer in the preview stage.
The only catch is that you have to figure out how to 'pack' what you want to calculate/execute into a Job but somehow not have to rely on the Unity API calls that are restricted to the main thread.
Generally this means only using pure data types such as Vector3.
If you use the special Burst-compatible data types such as float3, you can have your Jobs 'Burst-compiled'. This is basically a free 25x performance increase.
But for now I would advice:
- Use Physics for motion updates.
- Use draw call batching or mesh instancing for rendering.
wait, if i'm using the physics engine for handling movement, does that mean all my bullets need a rigidbody? right now i have no rb on them
Yes.
You also don't have to do collision detection yourself anymore. You can now use Colliders for this.
oh i've been using physics.overlapcircle to handle collisions
If you need to execute certain code upon collisions, Unity has special API for this.
Lol I guess that also works.
I often use Raycast for bullet intersections which also doesnt require colliders (although the object the bullet will hit does need a collider).
Up to you to decide how to approach collision handling.
alright cool
how do i choose more modern .net versions
it doesn't give me the same options as here
also, i have the vs solution turned on, but i cant access the build settings inside vs
Modern is the only option you have in recent versions of Unity afaik
wdym
so .net standard 2.1 is .net 4.7.2 or whatever?
in that case, why cant i see the assembly properties?
Assembly-CSharp -> Properties
i found the setting
it wasn't set to 4.8, actually
nice
C#10, baby
wow it's almost like writing Java now
atm unity supports all of csharp 8 and a subset of csharp 9
@cedar ledge No reaction gifs please.
FWIW i rather enjoyed that particular one ๐
1984
re: conversation a few hours ago @stable spear @sly grove .. bigdecimal implementation is complete and somewhat tested.. I spent more time than I'd like to admit writing the "big number to english" methods using the Modified Conway-Wechsler system (https://googology.wikia.org/wiki/-illion)
these numbers work up to 10e3000 or so
i mean, the english conversion part
"novemnonagintanongentillion"
what will people be doing with all this money
heh
our game's soft resources are energy (joules) and matter (quarks) so I'm sure we can explain away the nonsense of the absurdly large numbers
A clicker/idle game I assume
a bit - less clicker, though
even in the real universe, the total amount of energy goes up to no more than 10^80
a third of the game is the idle component that I'm building now, another third is the 1v1 battle component thingy you've likely seen, and the last third is the collection mechanic
good thing we're not limited by the real universe
technobabble handwavey quantum tunneling discover new universes atomic folding blah blah blah
that's number of atoms
i'm not a content creator i just write bad code
I figure each atom has no more than 1 joule
the nice part of my nonsense i made today is that it's really a small struct.. basically:
public struct BigDecimal : IEquatable<BigDecimal>
{
public decimal Mantissa { get; private set; }
public int Exponent { get; private set; }
.. snip a whole lotta nonsense ..
}
i think 22 bytes uncompressed
actually I don't know about that, i don't know what the overhead of a struct is
20 bytes exactly
16 for the decimal and 4 for the int included? = 40 total?
or you're saying there is no overhead
16 + 4 = 20 yes
ah, cool
there's no overhead if you're just storing it on the stack (e.g. as a local variable)
several bytes of which are unused flags on decimals ๐ but i can live with that
Oh, there might be padding if decimal had an alignment requirement beyond 4
Presumably it doesn't
my data structure packs down to 4 bytes with MessagePack
i thought i'd have to give up a lot in terms of network size but that's pretty good.. messagepack is black magic
uh. is that assuming all the numbers are the same?
I think MessagePack does some stuff like - if your int is small it shoves your 32 bit int into maybe 5 bits, and then shoves other data right next to that, etc..
so if your numbers get larger they may not pack down to 4 bytes
it is very slick though
Ah, you're right dox, it does get a little bigger as more non-zero bytes get used
looks like it caps out around 33 bytes
And of course, now that I watch this I realize that I probably should have just gone with a float since it gives me more than enough precision and I could have faked the equality part for values i care about
ah well i'm done mucking with it for today
@sly grove yeah.. like I said.. black magic. https://github.com/neuecc/MessagePack-CSharp/blob/master/src/MessagePack/Internal/UnsafeMemory.cs
I have virtually no idea how this works but... I am glad that it does
consider also double if you need more
Yeah.. probably not, tbh. I think most of the time I only need 4-6 sig figs. Decimal was attractive so I could do native equality with decimal.operator= for small values
why would you need to do equality?
at small levels - ie, before they've gone postal with exponential, the next generator will cost a human-readable amount, ie, "10 joules"
so the number the user sees will be ticking up every time the generator "cycles" (ie - every 10-20 sec)
it would be weird if the user had a float joules of 9.9999999 even though the game says it pays out "1" per cycle or whatever
I was just hoping to avoid any of that float nonsense
in reality it's not that big a deal - i could have rolled my own operator= and just hidden epsilon issues away from the client entirely.. but.. i started down this path this morning without having thought of that
tbh it might not be that big of a refactor, since really all that's exposed is a mantissa (deci-float-ish-thing) and exponent (int)
eh?
you didn't answer the question.
even with decimal, equality is going to be too unstable for a meaningful comparison between different calculated values
with a float/double you can always round before printing
(already posted this in General Code) Does anyone know the best way to access/alter the axis speeds for a Cinemachine FreeLook camera? I'm trying to make it so the camera will only move when the right mouse-button is pressed
Hey everyone I come here seeking knowledge.
I've recently re-downloaded my project from perforce and the only problems that I am getting are the following:
It's a third party plugin that I just updated and it doesn't seem to want to detect the other file which is living in the same project (abeit in the Editor subfolder)
Any ideas if the assembly references are causing this? I've been pretty stumped and my lack of experience with dlls and assembly references is showing here. I'd appreciate any insight on the matter. Thanks guys!
This is what my solution explorer looks like. I actually had never seen those -firstpass projects before. and I don't know what do different projects mean and how those might affect compilation.
Looks like some is in an asmdef while the rest is in the default assemblies
I have no idea how to move those over to other assemblies. What's the difference between an asmdef and default assemblies ?
I've looked online extensively but I can't seem to find the answers I'm looking for.
it's public, not internal. idk why it's complaining
Assembly definitions are files that manually define assemblies in a project https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html
They make for great separation of concerns, manually defining how assemblies are referencing each other
improves compilation time in some cases
Editor folders under assembly definitions do nothing, only the asmdefs define what assemblies are used when they're a part of the folder structure
It's hard to know what's wrong without knowing where those two files are in your project in relation to the assemblies
It seems though that you have one file in an asmdef relying on another in the editor assembly. Scripts in assembly definitions cannot rely on scripts in the default assemblies
What would you suggest I do to fix this? Move everything to the same assemblies?
this is annoying.
I'm unsure how you got yourself into this. You could remove their assembly definitions, and that would fix it.
The "proper" way is to learn assembly definitions and reference things properly, but that's a lot more work.
Yeah right now the project won't move forward too much into the future, so occam's razor is good now.
How would I remove their assembly definitions? What does that imply? Is that set up in unity or in vs? Is it some sort of file?
search for t:AssemblyDefinitionAsset in the project
Any case, I'll do what you suggest.
Hmm... My vs project can't find t:AssemblyDefinitionAsset in the solution.
Should I just straight up look for .asmdef files in the project and delete them?
Not VS, Unity.
OH
IT FREAKING WORKED
THANK YOU
Oh my, i had been stuck with this for weeks. It was until a moment ago that it occured to me to ask here.
Thank you so, so much.
Damn looking at advanced code scares me...
Hello,
I'm using the function newMesh.CombineMeshes() to combine a mesh that is over Int16.MaxValue (65536+ vertices).
To do so, I'm setting the newMesh.IndexFormat to UnityEngine.Rendering.IndexFormat.UInt32 but once the newMesh.CombineMeshes() occurs, event if the format is well set and that the mesh has 69k vertices, it only combine to 65536 vertices
I'm using CombineMeshes() with only 1 CombineInstance, could it comes from there ?
Guessing combine mehses doesn't support uint32
https://forum.unity.com/threads/solved-mesh-combine-and-65k-limitation.541496/ claims that it does, as long as the target mesh's index format is UInt32 (which it sounds like it is in this case).
I'm trying to download a .hdr image at runtime to use for a skybox. regular jpgs and png's work fine with the built in texture downloader method, and hdr works fine with the shader/material when imported at editor time. but whenever I set it at runtime it gives the dreaded question mark texture. what am I missing?
the hdri importer is most likely part of the editor
meaning its not available in build
UnityWebRequestTexture only supports JPGs and PNGs containing colour data. For other formats you would need to either use a third party library, or download it as raw texture data and load it with Texture2D.LoadRawTextureData.
Yes but I think that it's not supporting more than 65k for each CombineInstance in the array. I tried to duplicate my CombineInstance, and with my 69K vertices mesh, it combine to a 131072 vertices one. So it goes over Int16.MaxValue easily, but for one CombineInstance it doesn't, cause 131072/2 = 65536
Thanks, missed the jpg and png only bit. trying with the raw data loader now
Alternatively ImageConversion.LoadImage might be able to load EXRs? The documentation is ambiguous.
it may load it but pretty sure the sphere etc wrapping is done in editor only
the builtin panoramic skybox shader handles the wrapping fine (regardless of texture passed to it), just trying to work out the download part ๐
wellll at least something is loading now! probably on the right track, thanks for the help!
Is it to be expected that GetComponentsInChildren does not work with generic interfaces? i.e. GetComponentsInChildren<IMyInterface<SomeType>>(). For me it returns nothing even though it should
public Action<BucketMarker> OnMarkerClicked;
private void Start()
{
OnMarkerClicked += FocusToMarkersPosition;
}
``` Hey, I wonder if I need to unsubscribe the Action in OnDisable function like we do in "delegates"?
Action<T> is a delegate, if you need to unsusubscribe to clean up dangling references you should
but in unityevent we do not need. right?
How do I make a checkpoint gameobject inactive when the scene is reloaded from a save if it has already been activated?
myCheckPointGameObject.SetActive(false);
your objects have to check what "stage" they are in, i.e. if you have somewhere a flag "LoadingFromSave" set then in OnEnable the object has to handle it accordingly instead of doing normal activation routine
or whatever the analogous reasoning would be in your architecture
Have you already implemented a save system and if so what type are you using?
I'm using this save system: https://github.com/IntoTheDev/Save-System-for-Unity
And my current script is here: https://paste.myst.rs/sxo9a4jw
Save System for Unity with AOT (IL2CPP) and assets references support. - GitHub - IntoTheDev/Save-System-for-Unity: Save System for Unity with AOT (IL2CPP) and assets references support.
a powerful website for storing and sharing text and code snippets. completely free and open source.
I wasn't aware that it didn't work. But nonetheless you can write your own helper method to iterate over all child Transforms recursively. In each transform do GetComponents for MonoBehaviour, and then try to typecast it to your generic interface. If the typecast passes, simply return the component
Does anyone know of scripts I can use (even if they're not free) for culling cubic voxels that aren't seen by the camera before I send them to the renderer?
for example: a script that takes in a list (or an [x,y,z] array) of cube positions on a grid and the camera's position, FOV, angle and outputs a list of cubes minus the occlusion culled ones
how are you rendering them? I assume they don't all have their own MeshRenderers?
a surface shader and Graphics.DrawMeshInstancedIndirect
I think you'd have to do the frustum culling on the GPU in this case
Looks like some people have done this... https://forum.unity.com/threads/gpu-frustum-culling-is-working-now-but-how-to-write-lod-occlusion-culling.702596/
Though I'm not exactly sure what technique(s) were used
Seems like they're using a separate compute shader to do the frustum culling.
Is this moire effect from the graphic or is it a photo of a screen?
There's a way to get interfaces, but not like that
FindObjectsOfType<MonoBehaviour>().OfType<IMyInterface>().ToArray()
Then you just need to filter it for children
Its better if your interface has a non-generic parent interface which you can use
Or I think you can do:
public interface Example : IMyInterface<SomeConcreteType>```
and have your class implement that
and then search for that ๐ค
I'm not at my computer but maybe FindObjectsOfType<MonoBehaviour>().Where(i => (transform.children.Contains(i.transform))). OfType<IMyInterface>().ToArray()
I don't think the generic typing is the problem
It's that getcomponents doesn't find interfaces at all
