#archived-code-advanced
1 messages ยท Page 38 of 1
So you can do
newList = new List<float>(oldList);
It will create a new List that holds the same items as the old one, but that does not point to the old List
ok, thank you very much
public float maxTime = 1000f;
IEnumerator CheckChance(float floatValue)
{
float chance = 0.5f;
floatValue = Mathf.Clamp(floatValue, 1, 200);
float time = (floatValue / 200) * (maxTime - minTime) + minTime;
while (true)
{
float random = Random.Range(0f, 1f);
if (random < chance)
{
AddMoney();
yield return new WaitForSeconds(time);
}
else
{
yield return new WaitForSeconds(time);
}
}
}``` Someone know how I can make it, so it is Updating the function based on the time and the InputfieldValue. I want it, so when the InputfieldValue is 1, the seconds are 1. When the InputFieldValue is 200, the time is 1000 seconds.
Can use a remap function to do that. It's a combination of Mathf.Lerp and Mathf.InverseLerp that will remap your 1-200 range to 1-1000.
I already got it.```private IEnumerator CheckChance(string inputFieldValue)
{
inputFieldValue = PlayerPrefs.GetString("InputFieldValue");
// Try to parse the input field value to a float
if (float.TryParse(inputFieldValue, out float floatValue))
{
floatValue = Mathf.Clamp(floatValue, 1, 200);
float time = Mathf.Pow(floatValue, 1.6f) * 10f;
Debug.Log($"TIME IS {time}");
yield return new WaitForSeconds(time);
AddMoney();
}
}``` How can I make it, so it is not constantly calling the Addmoney function after the time?
{
// Get the current value of moneyValue
moneyValue = PlayerPrefs.GetInt("MoneyValue");
Debug.Log(moneyValue);
// Get the text/value from the input field
string value = inputField.text;
Debug.Log(value);
CheckChanceCo = CheckChance(floatValue);
StartCoroutine(CheckChanceCo);
}````
Is this repeatly?
yes every frame Update is called
Yes, this is ran each frame
How can I change it?
Change Update to Start?
If you need to only call it a specific times you can use a bool value and an if statement that will only run the method when it's true, for example
i'm not sure what you are trying to accomplish though (one off or every so often)
Hello everyone! I'm looking for a solution for calculating the part of screen coords of camera frustum that is under the ground (below 0 on Y).
Essentially I want to show some picture on that part, to achieve this effect, but without 3d model.
I don't need code, just a way to calculate it ๐
Thanks!
I want it to call the AddMoneyFunction after for example 10 seconds, then after 10 seconds again and so on
So repeatedly, use a coroutine for that which yields 10 seconds
(To my question above)
But instead of the 10 seconds, I want the time, that is calculated in the CheckChance Function
you could use a custom render feature if use use URP or HDRP
or a post process if you are using the build in pipeline
Yes, I use URP. How do I take advantage of it?
Then pass the time as a parameter to the coroutine. Or have it in your class if it can change while the coroutine runs
while (true)
{
Method();
yield return new WaitForSeconds(waitTime);
}
Sorry, I don't understand the approach. Can you please elaborate on it?
you could use that to render a object of your choice as a overlay
or i may have missed some information
That's the thing, I don't want it to be an object, I want to render it as UI element with moving texture.
It's a loading screen, essentially.
ah ok
so ui should work?
Eventually, I want it to be a canvas that appears at the part of the screen that is under the ground
Is this for the update function or what?
No that would be in a coroutine
Use a bit of logic, you cannot yield when not in a coroutine
should be possible to find out what screen position that corresponds to the ground place intersection the near clipping plane
assuming the ground is flat
Yes, that's exactly what I need. But I don't know how to calculate it ๐
is the y position of the ground known?
It's 0, yes.
quiet the brain tease
mmmm
I'm thinking about calculating this like camera.position + camera.forward * cameraNearClipPlane
Then always set y to 0 and calculate it's point on the screen.
in theory you would have the edge points of the Near clip plane of the camera
If you would draw a line from the top to the botton one and the solve for y been 0
then you would have the point on the outer edges that have the y position at 0
Lemme try ๐
I have this dialog box that is dynamic and showing little prefabs for all of a player's crew. There's 65 crew, so this dialog box is doing some .. heavy lifting on Instantiating these prefabs. The performance sucks though - 650ms to open the dialog. Any ideas on how I can improve this? 400 ms to initialize the icons themselves..
I don't know that I can just create the dialog and cache it since the crew are changing all the time (that's pretty much what the gameplay is.. creating clones, assigning them to missions, etc)
It looks like a big chunk of the instantiate time is on the setting of the sprite. Any tricks to optimize that?
that seems wrong
I mean, it's not much time - just 9ms, but.. doing it 65 times adds up maybe?
Well, it's my understanding that the atlasing and packing isn't optimized in the player/editor
Maybe this is a non-issue in builds
looks like almost 80% of that call is the file/read stuff
png, i think
I'm sorta not directly reading them, but not sure if that matters - I have an SO that has the references and I get the reference to the texture through that
Maybe that's where the file reading is being done?
hmm
in order to load the image, if i graphed the dependencies of unity assets between the code and the image, would there be any assets that were loaded with Resources.Load?
looks like the most time is literally just:
UnityEngine.UI.Image.sprite = UnityEngine.Sprite;
okay try this
okay
when you get back, try dumping all the sprites onto a Sprite[] on a game object in your scene.
and then see what happens
Sorry, had to get the door. I'm not doing any Resources.Load calls myself, but I don't know what's going on under the hood for how SOs manage themselves
What do you mean dumping them all into the scene? Just.. a naked object that I assign a bunch of sprites to?
I mean, I have several thousand sprites in the SO library
It worked, I think. I calculated screen position of ground on screen and placed my UI there, so it always under the ground.
Thank you!
They're also nested, if that makes any difference.. IE, there's a CrewDatabaseSO that has all the CrewSOs, each of which have a bunch of poses and wave files and stuff
i have a version that is not quiet there yet so nice that you got it working
You tried it yourself?
yes i was going the plane intersection route
yes
a naked object
it will force them to be loaded
in a clean way
@lime vinehttps://hatebin.com/fdzliqwpor
this will resolve if it's a feature or a bug
right now it sounds like possibly a feature
I'm thinking that the bottleneck here is actually loading the scriptable object textures in.. It's hard to google this since it's a bit more advanced. Is there reference source available for unity? I forget, or don't recall what pricing tier it's attached to
if the scene references the scriptable objects, and the scriptable objects reference the textures, they are loaded
on scene load
so right now it sounds like a bug
I mean I suppose alternatively I could load all those textures into memory at the start of the app and keep them cached instead of on demand, but that seems maybe wastey if a user isn't seeing all of the crew all that often
they are already loaded in memory
Oh that's so kind of you!
I saw this solution once for obstacle avoidance
the scene doesn't unfortunately, i'm finding it on demand
define finding
via resources.load ๐ ?
no, but i had to double check
my two normal methods are to either FindOBjectOfType (usually only for low volume MBs) or to manually link it
and in this case, I'm manually linking it to the prefab
@humble onyx https://hatebin.com/pupupldpwq mine
as long as this game object is in the scene, it has transitively loaded all the sprites
you ought to see them in the memory profiler
well, this isn't since it's a prefab
way simpler ๐ nice
is the prefab referenced in the scene?
I never use resources.load
so .. there's a single MB in the scene with nested prefabs and/or MBs that.. have references to the prefabs they need
lemme snap this particular one in the hierarchy
Yes, surprisingly easier than I thought. Probably should've asked in #๐ปโcode-beginner ๐
yeah
you will see it in the memory profiler
i think this is probably a bug then, maybe related to a compression setting, an atlas setting,e tc.
as long as the path of dependencies between an object in your scene and the sprite does not transit a resources.load, you are directly referencing and hence loading the sprite on scene load
PrimeIconV3(Clone) is an instance of the icon prefab - the SelectCrewPanel creates a bunch of those, but the prefab is linked to that MB so it's never loading it from a Resource
that's how unity knows what to build into your game, and why it must build the entire contents of Resources/ directories
ya
hm.. so should I still try that Sprite[] object?
well
this is a bug
it shouldn't be doing that
unity*
so my first try would be that
because there might be something iffy about the sprites
It could be related to player/editor behaviour (ie, the textures aren't optimized)
hmm but i've done this so much and so many times
i've never seen it
i've seen some weird apeparance of stuff double-compressed due to atlases but that's it
like.. i'm not familiar with the build process and how it optimizes/changes how textures are referenced, but that seems like it would make sense to me
but since opening/closing this dialog is a pretty hot path item.. 600ms is really unacceptable .. and it seems like ~350ms of that is file loading
see what happens
oh cool this is interesting, if you click on the file.read in the profiler, it "bloops" the asset in the hierarchy so you can see what it is
it's definitely the textures
so .. I'm assuming that this is just reading the texture directly from disk and .. i'll have to do a build and see if the same performance problem is on the final product
ha - nothing to do with "Normal" in the math sense or "Uniform" as in homogeneous
That's Dr Bubbles....... wearing his Uniform...... in a Normal pose (versus Victory or Defeat)
i gotchyu
Yeah like many of the characters have happy/sad/casual/etc poses for all the cutscenes
our artist is pretty damn good
etc
I'm gonna defer digging into this for now.. I will have to test/profile this in a build to see if it's the same.. I also have been meaning to upgrade the version we're using before then anyway, just in case it's some bug that's been fixed in the last year or whatever. ๐คทโโ๏ธ As always, thanks for your eyeballs and brain cpu cycles drp
Another profiling question for anyone:
450ms as I load my main scene. I haven't caught it yet but it seems like this sometimes takes 5+ sec. Restarting unity always fixes it. Should I care about this?
How would I properly do something like this in Unity?
bool alreadyTaken = false;
Monitor.Enter(_lockObject, ref alreadyTaken);
if (alreadyTaken) return;```
I watched a video on how to compress a unity file into one .exe file. It told me to use winrar. My question is will other people need to have winrar installed to open my now compressed .exe file.
Full function
private async void TryStartCountDown()
{
_timeLeft = _animationLengthAfterLastMoveInSec;
bool alreadyTaken = false;
Monitor.Enter(_lockObject, ref alreadyTaken);
if (alreadyTaken) return;
Debug.Log(_timeLeft);
while (_timeLeft > 0f)
{
_timeLeft -= Time.deltaTime;
await UniTask.NextFrame();
}
_boolSetter.SetBoolToFalse();
}```
i imagine so, i've never heard of compressing to an exe
Well if it's a big scene, obvs it's gonna take some time to load
are you talking about a self extracting winrar compression (i did a quick google)
they would still need to run the game exe afterwards (i'm assuming as in can't see anywhere where it says you can run something afterwards) where it was extracted to
_boolSetter.SetBoolToFalse()........?
I have so many questions
The thing is, my method (another one) is executed very often and executes this one, this one's intention is to execute the last line after the first method wasn't called for a while
But I don't want it to be called multiple times
Well I'm not sure how it works. but the video basically puts all the normal 5 files you have in a Unity project where you compile it into one .exe. Then you can open it and when he did it, it looked it was extracting something before running the game
K just .. not sure why you're not using something simpler instead of trying UniTask and async and ... "boolSetter" which is .... like, memeworthy, perhaps unintentionally so
only one will run at a time on the main thread, which I hope you're doing because that Time.deltaTime call is not threadsafe
Ah my stupidity
maybe you don't need winrar installed as the exe has the decompression code in it
you could test by using a different computer if you have one
or uninstall winrar after you've made it
Yeah that's what I was thinking. Thanks for your help!
@flint geyser what are you trying to accomplish? you want a countdown and one that's "smart" and can be called multiple times without resetting?
๐
Solved already
Context: I'm currently working on procedural terrain generation & I'm trying to make it more varied/interesting. I'm looking into mixing different noise patterns("biomes") using a larger/softer noise function.
Question: How would one structure a system that fulfils the following requirement,
- Allows the developer to create new noise patterns (from a set of functions, like presets) & edit them within the inspector
I have the usual parameters like number of octaves, lacunarity, gain, altitude & frequency. Will probably add vertex color to the list.
I'm not sure what you mean - you already have a working terrain generator with those parameters..? Why not just expose them in the inspector with a button to regenerate the terrain..?
If you're looking for better noise generation, I always lean on Perlin noise, it's just.. hard to beat
I'm already exposing the parameters in the inspector.
What I'm looking for is a system to expose them "per noise pattern".
Say I have a few different noise functions: perlin noise, fractal noise, ridges.
I'd like to be able to dynamically create new noise patterns with those functions,
a noise pattern would then be thrown into the mix & applied only on certain areas of the terrain.
I'm not looking for better noise.
Ah, sorry, I understand. I'd probably use scriptable objects, then. Basically, stuff all your data points into a SO called "NoiseTemplate" or "NoiseMap" or something. Then in your MB that generates the noise, you either select/find/specify the SO you want to use, read the values, and away you go.
The SO is kind of like a file that saves your templates. You can also work with them programmatically if you want
So, example - I have these "crew". I have a crew database SO that holds them all:
Each crew has it's own data points:
and then I have some scripts that I can get the SO I care about, get the data, etc. My use case is different than yours (i'm holding images, wave files, etc) but it's the same idea - in the SO you can put any data points you want
Alright. I had a slight suspicion scriptable objects was the solution. But I'm really not familiar with them, so I guess it's time to learn.
Thanks for the explanation, will have a proper read through it.
Then if you wanted to make a new template, you could just right click in your hierarchy and create a new template (or copy and paste an existing one):
(assuming you have a line of code in your SO that adds this to the editor)
Seems very handy!
Neat! Will have a look at it.
You can also use SO's to do this in a way. Have a base class with a function you call and then you can inherit and override it in new classes. Then that allows you to set the SO with the code you want in the editor (also exposes variables for the custom code in the SO)
I can make an example of how that would work
Does mean that if you want to add a completely new noise pattern function you'd need a new SO script to store it in
An example would be much appreciated.
I think I need to get a grip of SO's before completely understanding this.
it is an unusual way to use them (i use it for 2d tile custom code)
one sec i'll make an example
public class NoisePatternBase : ScriptableObject
{
//Add whatever you need to return and any external parameters
public abstract void NoisePattern();
}
[CreateAssetMenu(fileName = "NoisePatternOne", menuName = "ScriptableObjects/NoisePatterns/NoisePatternOne")]
public class NoisePatternOne : NoisePatternBase
{
[SerializedField]
private float float1;
[SerializedField]
private float float2;
//Same returns and parameters as base class
public override void NoisePattern()
{
//Use float1, float2 with this noise pattern
//Create multiple types of this SO to have varying float1, float2
//Custom noise pattern code here
};
}
[CreateAssetMenu(fileName = "NoisePatternTwo", menuName = "ScriptableObjects/NoisePatterns/NoisePatternTwo")]
public class NoisePatternTwo : NoisePatternBase
{
[SerializedField]
private float float1;
[SerializedField]
private float float2;
[SerializedField]
private int int1;
//Same returns and parameters as base class
public override void NoisePattern()
{
//Use float1, float2, int1 with this noise pattern
//Create multiple types of this SO to have varying float1, float2, int1
//Custom noise pattern code here
};
}
Then you store these SO's as NoisePatternBase in your code
and then call NoisePattern() and it'll get the overriden method depending on the SO used
So you make SO's with the custom noise pattern code and then can create assets with the different variable values for each noise pattern type
Yeah, that looks fairly logical
Thanks for the tips! Will definitely try something like this
I don't recommend messagepack, it's a headache to get running. better make your own serializer
I couldn't imagine trying to write my own serializer that works anywhere close to messagepack in terms of performance (size), performance (de/serialization), ease of use (literally just annotating each member I want to serialize), and so on... Why would you want to write that yourself..?
that's what i did a while back for networking. Was easier than trying to coax messagepack to work with il2cpp
but yeah it seems amazing, haven't been able to get it running on unity 2021.LTS. keeps returning the same "class not registered" error
how did you massage it?
make sure to swap the Api compatibility level in the Player Settings, fairly certain that whatever option is set by default is the wrong one for MessagePack to work
even with .Net it bombs
oh hang on, user error alert!
is there anyone who knows photon pun 2 that could help me quick
kk
boneweights won't serialize so i'd need to do my own soup anyway, will stick to jsonutility slow serializer for now
I'm not entirely sure if this is a Unity question.
If I wanted to release an update to my game for all players to have. How would I do that? Would an engine except Unity need to take care of that for me? My issue is that I may plan to update my game later, but if I give new players a new game, they'll have entirely new databases, since my game likes to keep track of each player's points, stuff they've unlocked, etc.
I didnt understand what does Component.SendMessage() do ? Can someone explain it for me please?
backend has to be IL2CPP using the AOT code generation tool of messagepack since android doesn't support JIT code gen
I'm using 2021.3.3 and it works no problem.. i have a separate project for the DLL containing the model files (since those model files are used both in the unity client and the c# console server), i just compile the DLL, run messagepack generator on it, copy the file to the unity project and everything pretty much just works
There's really not too much fuss to it, and I have hundreds (literally) of files keyed with messagepack annotations and it's pretty much no thought whatsoever.. then I just de/serialize it with one line of code
"1 author 1 change" ๐ it's been working for me without a lot of fussin!
You just... make a new version of the game and release it to the app store. If you're relying on local databases (ie, files or unity's libraries for storing some data points) then you'll need to identify if the user has an old version and migrate it to whatever the newest version is. You'll probably want to do that in a loop, and leaving the methods intact. IE:
while (UserVersion < CurrentVersion)
{
if (UserVersion == 1) UpdateToVersion(2);
else if (UserVersion == 2) UpdateToVersion(3);
.. etc ..
}
It's a janky way of calling a method on every monobehaviour on the object.......... as the docs state. Don't use it until you know why you'd want to. #archived-code-general or #๐ปโcode-beginner also
Thanks a bunch!
NP. It's a hard/complex topic, for what it's worth.. If you're using multiplayer and/or a common database, versioning your data has to be done with care, and you have to ensure that your migration is also tested and bug free. It's as much of a product as your game is.
Honestly though don't worry about it until much much later, IMHO. It's the kind of thing that you don't really need to even think about until you're 90% or more of your way to completing a project.. Or you'll just sort of need to build one (a set of migration scripts) along the way when you upgrade and your own dev account is out of date suddenly and you get tired of mucking in the data/json/ini/registry/database directly ๐
i figured it out, but god am i stupid
I already had the solution I just forgot that I had it solved
This code is horrendously bad if anyone wants to help me work through it and clean it up, I'm trying to develop a chat system between npcs. I'd like for one npc to be able to talk to another npc and increase or decrease friendship depending on the nature of the interaction. I commented all the code based on what I want to happen but it's just not quite working. DM me please if you're going to help me!
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.
anyone know how to split a generated mesh into different sections ?
A mesh by itself will only contain vertexes and indices, so inevitably you'll have to perform some sort of segregation on the vertices. You can access mesh vertices via Mesh.vertices.
In Unity, the index component is Mesh.triangles. You'll have to loop through those and remove any references to the vertices that you don't choose to keep, and these lost entries will represent the triangles that are getting chopped up.
I assume you're trying to bisect a mesh as to cut off a part of it.
More profiling woes. When I leave my computer (or unity) for a while .. even 15 minutes.. I get this huge lag spike in areas of my game. It only occurs the first time I'm coming back to Unity, subsequent runs take no time at all.. but it's annoying. Any ideas? (This one was 32 sec)
36*
Hm.. looks like a WONTFIX unity issue ๐ฆ
do you use more than 1 scene?
yeah
5 or 6
but i'm loading them async and only on demand
i'm on 2021.3.3 so.. i probably ought to just upgrade unity and see what happens, but... i'm afraid of change. ๐ Liberal personally, conservative technically
Hey doctorpangloss, I think you missed my poke from the other day. Totally fine either way. (:
pointer to a pointer, right?
๐ no idea .. i'll probably just upgrade unity and see what happens
I'd like to make a button change its text color to 50% alpha if it's disabled.
My current idea is to make a script, toss it on any button/GO that has a button and text in the hierarchy, sniff the values and update them accordingly, but.. it doesn't change if the button becomes disabled/enabled later. I don't think I want to put an Update() check for this, as there's a lot of buttons in my app and it seems wasteful to be checking 50 objects every frame.
Anyone familiar with UnityEngine.UI.UIBehaviourExtensions and the Invoke methods? The docs are really light.. ๐ฆ Specifically I'm wondering if this would work: https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.Tests.UIBehaviourExtensions.html#UnityEngine_UI_Tests_UIBehaviourExtensions_InvokeOnDisable_UnityEngine_EventSystems_UIBehaviour_
Here's my code so far: https://pastebin.com/DMMsJauX
Code review appreciated.
(this works but I imagine it's not scalable if I've got dozens of buttons in a screen, which some of my screens do)
You shouldn't need any code for this. Buttons already have a list of colors in the inspector for various states, including disabled
My understanding was that only works for tint-swap buttons.. I'm using sprite swaps
(It didn't work when I used the ColorBlock.disabledColor approach)
Some bugfixes (make it work if disabled and on the first frame): https://pastebin.com/UtCSsRDQ
I feel like this is reasonably fine, even for ~100 buttons. ๐คทโโ๏ธ It works so I'm probably just gonna move on to the next thing..
is there a reason why calling this method in a text asset load returns a null reference for the text asset even though this variable has the correct path?
ie using it like this
but it does work when there is a literal string with the same text as this would output inside
I can't imagine why the exact same path would have different results, unless maybe if the Resource.Load is being called at a different time when the data isn't ready or something. How far have you gone to ensure the two strings you've tested are exactly the same?
well
it probably doesn't have the right path
what does this mean
it's clearly the wrong path...
does anybody know if you can use transform.translate when working with rigidbody2d.velocity. I control my character with rigidbody.velocity, but I have a function that moves the character a certain X and Y using transform.translate, the only issue is, when the code for transform.translate is being ran(which will happen in update) the movement of the character starts to not really work and the character will move very slowly, any help? I am thinking it is an issue with using translate with velocity but not sure.
#๐ปโcode-beginner
and yes, the issue is that you are using transform.Translate which doesn't use physics combined with rb2d.velocity which does so the transform.Translate will override what velocity does
@thin mesa hmm ok that makes sense, do you know how I could use the rigidbody to move similarly to the transform.Translate function? I tried rb.MovePosition but that didn't seem to work either because that sets it to a position instead of adding the position
you add the amount you want to move to the current position and pass that to moveposition, however you'll still be overwriting what you do with velocity so you'll want to prevent velocity from being assigned for the duration of the move.
still #๐ปโcode-beginner though. if you need further help with it, then ask there and provide relevant code
Hey I want to ask if is possible to make Dedicated Server console input reader / handler.
Is there a way to stop a coroutine and then continue it from the same moment?
yield return new WaitUntil(() => myBool);``` inside the coroutine
and just set that bool false / true as you wish
I need it not for a specific coroutine actually
I want it to be so that I can start all coroutines and then continue them from the same point
nope
coroutines don't work that way
:<
not automatically anyway... You could do something with Time.deltaTime or some kind of global pause variable that all your coroutines listen to
ยฏ_(ใ)_/ยฏ
I think I can do it with reflection
Add this after every yield return
yes
I can send code but dont really want to summon the wrath of god doing so, so if there's a glaring issue with my approach before i send a bunch of spaghetti code pls lmk.
I haven't used classes and objects much before so forgive me if i use the wrong terminology. IK this isnt the optimal solution to a problem, but i have a text file I want to parse, and each line contains a bunch of delimiters to help with that. I made a class called dialogue that has a bunch of attributes. Then I made an array of objects, one for each line, and want to go through with parsing them so I can use them later.
Example of line to be parsed:
{2.01}[eejit](prompt:a:1)"Hi I need help"{2.02}
and the end goal is to have an object that has:
step: 2.01
speaker: eejit
prompt: true
action: true
choices: 1
text: "Hi I need help"
next step for choice 1: {2.02}
Why don't you just use JSON
Instead of making your own crazy file format and custom parser
Ive never done anthing with JSON, so it wasnt on my radar but I can look into that
Anyway you didn't actually ask a question
well
unity says i'm not initializing the object to even set an attribute, and I dont know what i'm missing to do so, because from everything Ive seen online it should be initialized already
This really seems like a #๐ปโcode-beginner issue
Post your code and errors there
got it, sorry
Hello, So I struggle a lot to find empty tiles. I have a function that find the ore but I want that it can respawn after a amount of time, on the available places. I donโt know if anyone can help. (I donโt know if this actually is an advanced question)
I'm trying to set an integer using the TMP input field, by doing this in a setter. Can this not work??
public string FloorNr
{
set
{
int.TryParse(value, out int result);
floorNr = result;
}
}
it's only getting set to 0
Doing simply Parse gives a Input string was not in a correct format error
you cannot pass the text field from inputfield to the tryparse. you need to use the text varaible from the child Text object
Hmm I see, I guess the On Value Changed is just a trigger
Pardon, I'm not sure if this is really an advanced matter, but no one has been able to assist in the other channels:
I have a 2D grid-based game with some randomly generated levels. I can spawn objects on the grid, but I want to randomly instantiate several 2x2 (grid cell) prefab objects as well, which should fit into valid patches of the cell grid (i.e. playable space, and not cut into walls).
Is there a best practice for evaluating available spaces that the object can go? I can think of many approaches to this, but my ideas all have either flaws or generate more overhead than I'd like.
For example, if I loop through the available cells, I can easily check if there's space, but then I am severely weighting the chance of instantiation towards the earlier coordinates. I want a roughly equal chance to appear at all possible positions. I could loop through and log all possible positions into a list, but that seems extremely cumbersome. I feel like there's an established method I'm overlooking. Any direction or reference would be greatly appreciated.
I would make a List of all possible positions and then remove from the List once a position has been filled. It means you only need to scan your grid once which will be much more efficient
sounds better than my idea of checking a random 2x2 grid until you find a valid spot
Ty for responding. This is the approach I'm currently posed to attempt. My key reservation is that I will need to still loop back through, since I can't really spawn any other objects in that time without inadvertently cutting off possible positions for the larger object. So, I'd need to do the full scan, choose the places and spawn those objects, and then a second pass to spawn the smaller objects.
I dont see why you would need 2 passes, just have a decision during the first pass large or small
Because if you take a 2x3 space, it presents two distinct positions for a 2x2 object, but if you decide not to use the first (for the large object), it's possible that a small object placed instead could obstruct the second, and then it wouldn't exist
(fixed that, was very unclear, sorry)
so what you are saying is you want to place all large objects first, correct?
sorry if this doesn't contribute:
would it be best to spawn the most space consuming objects first? in the above scenario, you'd be able to place the 2x2 object anywhere, remove those 4 blocks from the pool of valid 1x1 block locations, then go from there?
Right I believe you've both stated the case as I understand it
I want to ensure maximum options, which I think logically requires the larger objects to be fit first
then you do not need to scan the grid to place the large objects.
say you want 10 large objects, just randomly generate 10 sets of non overlapping coorinates
It's like playing tetris, if you don't place them optimally you will need to skip some objects anyway. So even if you pick the biggest first it might not ensure you placing all objects you want.
^ I was afraid of that
I can't think of a solution to that unless you are fine with having variable quantities of the resources
Ahh, pardon, my initial description may have also been unclear. The scene utilizes something like a 32x32 cell grid, but much of that is not available. The level is randomized in terms of particular objects, but some aspects are fixed, so I am looking to plot around those. E.g. if there is a large river divide on a screen.
hm. the objects in question are obstacles?
that sounds like you must ensure at least one valid path between 2 important points
Variable quantities of the smaller items are acceptable, but should generally be fixed for the 2x2 assets.
The objects are a multitude of things, but most commonly:
2x2: Bosses, Dungeon entrances
1x1: basic enemies, resource nodes
assuming you move either up down, left or right
thankfully, pathing is already okay, but yeah a good point. Now, I'm just looking to place the 2x2 objects in a valid position. As long as it's within the viable area, pathing will be okay.
I gotta sleep, gl
ty for your consideration, and goodnight!
I think you will be ok doing 2 passes, a 32 x 32 grid is pretty small so should complete without too much delay
Sounds good. I think I'll do that for now at least so I can move on. Really appreciate your time and feedback, ty.
good plan
it might sound silly but depending on the exact circumstances, e.g if you know that the grid will generally have a lot of viable spots (>50% say), then just generating a random coordinate and checking if it's suitable, retrying until success, is likely the most efficient you can do
Right, in testing, this was fastest for me. However, a maximum limit on checks still needs to be put, and ultimately, this approach scales poorly to randomized scaling, if unique level layouts are used. I thought to offset that by actually checking if additional valid cells could be declared (e.g. bump a wall back a bit as needed), but that quickly becomes a very messy bit of logic.
There are some other approaches, like looping once, but declaring a random coordinate to start from, and picking the first available space. Making sure to set up the appropriate order of the loop is key, and it will likely be a rough facsimile of true random seed, but users might not notice.
For this size project, it still feels like the best overall approach for now will be to make two passes. It's a curious logic problem though, since it's fairly simple to pose as a question, but not intuitive for me to solve.
I can change the values on my post processing profile via c# but they seem to bounce back to the original a few seconds afterwards, can anyone help? documentation is as usual completely lacking
hi! currently trying to solve a bug where adding to an object's eulerangles doesn't end up giving the expected result, rather snapping it back and forth between the expected value and the value of a buoyancy script.
I'm only trying to add onto the Y rotation axis to rotate an object left and right.
this is the buoyancy script;
https://pastebin.com/usMxdtxC
i've tracked down the bug to the line
transform.up = GetNormalWS(positionOS);```
changing said line to,,,
```cs
transform.rotation = Quaternion.LookRotation(transform.forward, GetNormalWS(positionOS));```
allows it to rotate on the Y axis but breaks the buoyancy's x and y rotation
and this is the line that changes the eulerangle in another script, which we're trying to make work righto now.
```cs
boatParent.transform.eulerAngles += new Vector3(0,rotationSpeed,0);
any help is greatly appreciated in trying to figure this out.
thank you!
Can you take a video to explain your issue?
specifically, the Y rotation is supposed to continue adding smoothly, but in this video it keeps reseting (with the transform.up version)
and this is how it's supposed to act, only with the buoyancy script affecting it as well.
I see. Have you considered having separated anchor object for Y rotation as a child game object?
Not sure if simplest, but can't you cross your new forward instead of setting transform.forward?
Itโs also not a good practice to read and set eulerAngles back. The case sounds like you want to rotate your object around local Y axis not the world Y axis like eulerAngles
var up = GetNormalWS(positionOS);
var right = Vector3.Cross(transform.forward, up);
var newForward = Vector3.Cross(up, right);
transform.rotation = Quaternion.LookRotation(newForward, up);
Like this. Not sure if order is wrong on those crosses x) Too long time ago I used em.
Anyone have knowledge working with the A* plugin? I am having a weird bug where even though the walls are classified as obstacles the character still tries to walk through them but the "path" doesn't have them doing that. I will have a picture below as an example.
it worked!
thank you so much for typing it out, worked word for word :]
and yeah, both eulerAngles and localEulerAngles end up giving the same result, since the object isn't a child of anything.
didn't know it was bad practice
They wouldnโt have difference in that case, you need other way if you want it rotate around the axis after rotation since euler is applied in YXZ order
Anyways seems like your issue solved? or still have rotation issue?
Hello, is there anyone that could help me out? I'm working on a FPS, and I'm currently working on creating the AI aiming mechanics for the game. The bullet is a projectile however, with non-zero values for its mass and drag. I'm not sure how I can script the AI to aim at the player, taking into account for the projectile having mass and drag.
I can go into further detail if needed.
Oh, using actual rigidbodies... why?
why would you do that?
with drag too...
Mass shouldn't be an issue if you're setting the velocity initially, but drag seems hard. Seems like an awkward way to make an RTS, but if you really want to do something crazy like that I guess you'll have to do some math.
I guess you'll need to run a simultaneous equation between the velocity of the target and the more complicated behaviour of the projectile
This doesn't sound too advanced and more like backtracking physics equation?
I guess you'd need to know how drag affects the rigidbody
But that's probably well defined
I think unity uses simple linear drag
Drag just adds opposite force relative to the current direction of the bullet right? So if the bullet's going up, drag will pull it down, but if the bullet's going down, drag will push it up, and etc?
Probably relative to the velocity of the bullet
Yea that's what I was thinking
My initial thought is to use Quaterion.LookAt so the GunPivot (an empty that acts like a pivot for the gun gameobject within my ai gameobject) is lined up on the Y-axis, then do a numerical calculation using some equation, progressively rotating the GunPivot upwards every time the calculation fails.
Does gravity act on these too?
yea
Are you talking about the AI learning from failing shots?
I think they mean a search
So basically let's say that this equation that'll calculate the x-axis rotation value (which is the rotational value that rotates the gun up/down) starts with the value being 0 degress. The method would then run a while loop, simulating a bullet shot using a mathematical equation, and will stop running if the position of this simulated shot goes past the target or goes below the ground. Then the method would check if it went over or underneath the target, and would rotate GunPivot up/down accordingly. Then it'll simulate another shot. Keep this going until it hits the target or it reaches a point where it the method just rotates up then down then up then down... If the latter happens, just set GunPivot's x rotational value to a value in-between the 2 values. If the former happens though, just set the x rotational value to the value that will have the bullet hit the target.
My only issue is that I have no idea how to simulate the bullet
Are you sure you can't express the trajectory with a function?
Yea that's what I'm trying to do
Because I messed around with Physics.Simulate and that ended up crashing my computer every time I start the unity editor.
Then you only input the distance and starting height, and you get your output rotation.
Wait wdym?
I'm talking about writing the formula for distance with aspects of gravity and drag for your case as a mathematical function, and solving for your rotation. But I guess since you're gonna numerically compute it later with unity physics this would give some errors.
I mean I tried doing it analytically (since what I'm trying to figure out is only the launch angle), but tbh I have no idea what equation I need to use to calculate that.
This is my thought process however
So I would have a Vector3 hold the value for this calculation. I set this Vector3 (lets call it BulletTrajectory) at BulletSpawn, and add the InitialVeloctiy value into this vector 3 forward for the Vector 3 can start moving. Then at each frame, I'd add a Gravity value pulling BulleTrajectory downward, and also add a Drag value pulling BulletTrajectory in the opposite direction of where BulletTrajectory's going.
not each frame. I meant at each iteration of the for/while loop*
I think the incorporation of drag makes the calculation very complicated. So if you don't need it (which you might not for simple bullet) I would skip it.
alright
Since there would be no drag, I would assume that the bullet would now travel in a parabolic line now?
Since the only thing affecting it is gravity
issue was solved! sorry for the late reply hahah, the code jaws provided worked great :]
Anyone worked with version defines before?
They don't seem to be working for me ๐ค
I have the pictured version define in my asmdef, and TextMeshPro is NOT installed. Yet this code:
#if TEXTMESHPRO_1_4_1_OR_NEWER
[SerializeField]
TMPro.TMP_Text speed;
[SerializeField]
TMPro.TMP_Text localVelocity;
[SerializeField]
TMPro.TMP_Text velocity;
#else
[SerializeField]
Text speed;
[SerializeField]
Text localVelocity;
[SerializeField]
Text velocity;
#endif```
Seems to be compiling the top portion as I get:
`Assets/BetterPhysics/Runtime/Utilities/Speedometer.cs(12,9): error CS0246: The type or namespace name 'TMPro' could not be found (are you missing a using directive or an assembly reference?)`
Hmmm this should work, maybe it's installed from other package dependency?
Check if the Packages/packages-lock.json contains textmeshpro
it does!
But if that's the case why am I getting a compile error? ๐ค
Oh wait... I think I forgot a step here
I didn't actually add TMP as a dependency in this same asmdef
Do you still need that with a version define?
You need assembly reference
Hmm ok yeah that got rid of the error.
And version define (if installing TMP is optional to your package)
sort of a more abstract/high level question, but: is there any good guides or articles or something outlining what's considered best practice for the overall layout of scripts for the sake of managing game state and game logic? I'm a web developer with a handful of years experience so i have experience with like, web apps written in JavaScript but I'm having a little trouble trying to bridge my existing understanding into Unity and C#.
like is their some Unity & C# philosophy of design or library equivalent to React Redux?
not really. some genres have really rigid traditions and should all be engineered the same way - CCGs, racing, FPS, RTS, fighting, metroidvania platformers...
in terms of libraries, DOTween for programmatic animation and CineMachine for camera rigging come to mind. there are many high quality paid assets that, despite being made by 1 or 2 people, work really well
is there something in particular you wanna make?
at the moment I've got a game idea that's planning to be like, top down grid layout management style game, inspired in part by Stardew Valley.
have you read Blood Sweat & Pixels by jason schreier? he has a chapter with his interview with eric barone the stardew valley creator
worth reading to see what you are getting into
I've not, will have to add that to my reading list.
games like that are hard to author because kind of like CCGs they are decoupled in some places and tightly coupled in others
probably doesn't help that i also want the game to have like incredibly mechanically deep systems and machines akin to factorio, which is going to pose an exciting challenge in optimized state management
hmm
exciting... optimized state management
really depends on your goals
have you looked at the stardew valley source?
unfortunately i don't think i can find a decompiled version in github before the multiplayer update
is your goal to have a working game?
I've not
usually people who like optimizing state management also like factorio, like making that kind of game and liking something that frankly doesn't matter that much is pretty aligned
so i'm not going to give you a hard time for this... misconception
you can go ahead and lean into it ("optimized state management") actually. but you will not have a working game for a long time
i mean, yeah, working game is definitely the desire, but i also want to make sure it's something i can easily make progress on over time without having to tear apart systems and stuff, but mostly I'm just trying to hold in my head any kind of decent architectural plan that makes the next step to code/work on easy to figure out
this could illuminate what i mean - https://github.com/veywrn/StardewValley/tree/master/StardewValley
coupled: look at Game.cs. decoupled: well, there are a ton of components to this game
xna and unity are similar
(but yeah I'm not in a rush on this particular game idea, this is a sorta baby of mine i intend to fiddle with on and off for awhile and i can crank out small less carefully designed game ideas whenever I'm in the mood to have that instead)
well the simulators people actually play, almost certainly factorio included
they evolve a lot over time and have "crazy ants" architecture
i haven't seen factorio source specifically so it is hard to say for that game
dwarf fortress is a crazy ants architecture game, and stardew valley is more crazy ants than something you'd turn into a book
if that makes sense
the factorio friday facts devlogs are fascinating glimpses into how Factorio is written tbh, it's a bafflingly well optimized and carefully designed game lol
never purloined the source code directly myself but i imagine i will at some point as i learn game dev more
okay what i am trying to say is that it is the exception rather than the rule
and it's hard to say anything authoritatively without source code. at the end of the day they can write anything they want in their devlogs. not saying that it is untrue
it can certainly be an opinionated architecture
but other than for that 1 game in its 1 engine, can something help you write another game? hard to say
finding that stuff appealing can help author this kind of game
how much it matters in terms of actual substantive execution i don't know. i think it's overstated
we shall see i suppose ยฏ_(ใ)_/ยฏ
anyway i feel like i have some better idea of how to bite into things now
good good. imo the reason to choose unity for a simulator game is because you can quickly make something that looks good with relatively straightforward engineering.
things like DOTS or Jobs or Burst or whatever... you can try to jump directly into this stuff but it will not help you make something that looks good. in fact starting with these will guarantee you will not have a working game for a long time
Rimworld, an indie simulator game made in unity, is highly decoupled
and has a crazy ants architecture
factorio is really idiosyncratic. i haven't played the minecraft mods that inspired it.
@tacit coyote something like this - https://oskarstalberg.com/Townscaper
looks great in unity
really shows off "simulator" ideas without all the faff
so im trying to make an interaction event on the inspector tht i can add it looks like its trying to work but it doesnt pop up
I don't fully understand what this code does
you're just telling it to remove the component every other frame
and then add it back again
also you don't need the if statement inside the else statement
because the two conditions are opposite of each other
so the if statement will always be true
yeah that code is kinda nonsense, can not think of any context where that makes sense
what are you trying to accomplish @wild cobalt ?
then why is it also destroying one if its already there
also if just trying to add a requirement you need certain component, i would just use RequireComponent for that
the require component?
yea ive never even heard of tht lol
people generally learn of it before doing custom editors
lets you have it when you add your component it automatically adds the required component
and will not let you remove the required component in the editor till yours is
oh ok so it would add whatever i put in there automatically mhm kinda broken
hmm you might get better help in #๐ปโcode-beginner
Hello all, I'm new here thought this was the right place to ask.
I'm looking for am advanced programmer to help me with a nested loop operation.
I've got two working iterations but I'm looking to tidy up a bit and wondered if anyone with some more advanced knowledge than myself fancied having a look and having a go at simplifying my code, what I'm looking for is extremely specific so if you like a challenge and know your stuff let's connect.
for models in 3d we can use the unity overloads OnBecameVisible and OnBecameInvisible to know if a model is being rendered by the camera or not.
Is there something similar for the UI ? i have a UI panel that has a countdown and i dont want the countdown to be working when this panel is 'hidden' (Im actually not disabling it it im using CanvasGroups
just wondering if the MonoBehaviour can check itself if its being shown
If you're looking for a team/partner then maybe you should post in #๐ปโunity-talk
If you need help with code then just show the code you need help with and ask the question.. Like Uri said "Don't ask to ask"
I don't know how to post code in a readable manner
So here
for(int o = 0; o < _Values.valuesBools.Length; o++)
{
if (!_Values.valuesBools[o])
{
for (int i = 0; i < _Values.valuesAmounts.Length; i++)
{
if (_Values.valuesAmounts[i] > 50)
{
if (Physics.CheckSphere(SphereCentre.position, SphereRadius1, _player))
{
foreach (GameObject graphic in _Graphics) // for each graphic turn them off
{
//graphic.GetComponent<U10PS_DissolveOverTime>().CheckKey();
graphic.SetActive(false);
Debug.Log(graphic.name + "Turned off");
}
int r = Random.Range(0, _Graphics.Length);
_Values.valuesBools[o] = true;
GraphicChange(_Graphics[r]); // here we set the graphic to use from the variable above;
//StartCoroutine(ChooseGraphic());
}
}
}
}
}
I want this to instead of looping through via iteration, to loop through and select.
Then compare the selections value data and make changes based on the return.
But it's so much deeper than this simple nested loop.
I just made this to give an example of what I'm working on
#854851968446365696 says how to post code
look into inverting the conditions into guard statements to early exit and reduce nesting - you could also look into using LINQ (will allocate), though it looks like your structure may be awkward for it (separate lists with implicit index?)
Yes I've three arrays that need checking.
Premise.
User has a set of values as floats
User does something and value changes
I want the universal script I can place on many many.objects to understand exactly which value it's looking at and determine an action based on its size.
I'll look into inversion and guards that's a great starting point thanks
This is also all networked so there is a single script on each user solely as an identifier for use in the universal graphic script
I'd think there's better architecture you could use for this problem, i.e have the user notify the universal script when a value has changed to be above 50, rather than constantly iterating and polling every value for every user
if this is working though and you'd just like to make it more readable, then it seems like you just want a small bit of refactoring to reduce nesting & extracting blocks to other methods
Your pretty spot on with what you've said.
It is working almost exactly as I want.
The actual code is 300 odd lines
But yes it's working as intended.
The problem with sending data to the script is I will have hundreds of them across the world.
But currently they're universal and based on a sphere check.
So they only trigger when a player is near.
What I can have is players sending data to hundreds of scripts that then do something with it if a user isn't nearby.
I may be overthinking this.
But you've given some good points to look into so than you
#854851968446365696 on how to post code. And I think asking you to to add some guard clauses to this code is not against the rules.
It just hurts my eyes to see the nesting
I've rewritten parts of it now I'll learn how to post and resend
anybody know how I can turn off an ISystem from a MonoBehavior? Trying to access it only gets me a SystemHandle and I couldn't find any easy way to access it's SystemState to set it to Enabled = false
Are new strings generated every update iteration? Meaning is it bad for performance? As I think it needs to be handled by garbage collector and if it creates every string object behind the scenes every time that is not good. should I cache these strings?
everything that you hardcode like that is a compile-time constant and is only allocated once
hey guys, can anyone help with this one?
given a string, lets saying "the quick brown fox jumped over the fence".
Given an index, let's say 4, retrieve the word from the string starting at that index. A 'word' is any combination of chars encased by spaces.
So it'd return "quick".
So far, I take the whole string, and use string.Split(" "), to get list of words, but then idk which one is the closest to the index provided in the string
I guess I can then use string.IndexOf(word), but that seems so rough and poorly coded
Could someone please tell me what the hell is going on with this bounding box I tried to generate... It's way too big on the right side and that makes no sense ```cs
var parentPosition = ARManager.Instance.instanceController.sceneRoot.transform.position;
var parentRotation = ARManager.Instance.instanceController.sceneRoot.transform.rotation;
ARManager.Instance.instanceController.sceneRoot.transform.position = Vector3.zero;
ARManager.Instance.instanceController.sceneRoot.transform.rotation = Quaternion.identity;
Renderer[] renderers = target.GetComponentsInChildren<Renderer>();
var bounds = renderers[0].bounds;
foreach (Renderer renderer in renderers.Where(x => x.gameObject.activeInHierarchy))
{
bounds.Encapsulate(renderer.bounds);
}
There are no hidden objects, everything is visible, I made sure to reset the rotation because that messes with the bounding box generation as well but it. just. will not. behave
Hey, my game takes place in the space, and the game has a huge scene, and I'm currently trying to add pathfinding to it. A* is prob the way to go, but taking in account that my world is huge there's no efficient way of creating a grid, so it has to be dynamic. Is there any algorithm that solves my problem, or should I find a way to make the grid dynamically generated?
@blazing verge The complexity of a pathfinding algorithm depends on the number of obstacles and not space. Also, I do not know how the A* solution of unity operates in 3D space. (The algorithm works in 3D) Personally, I would create node that would define a highway and an other algorithm for finding the path to the highway from any place.
Unity does not have built-in a* solution that works without walkable planes (nav mesh), so that's why I'm making my own. What do you mean by highway?
I assume he means having very sparse nodes inbetween regions of interest
Well, I have player's spaceship that constantly moves, and I need to add bots, that will follow the player, so the player moves themselves, and other bots move too, so I'll probably have to recalculate the grid each frame while also making it dynamic depending on position of the player, I guess
I just thought there was already working algorithm for that
Start by trying to use a lerp on the player + a teleport when to far or stuck.
You will probably never have obstacles between the player and the bots. You could also keep in memory the path the player took and reuse it.
For a follow, most of the time, there is no need for pathfinding.
do you mean from the player loops? or are you talking about a DOTS thing?
DOTS. trying to stop a dots system from a monobehavior
Might try your luck over in #1062393052863414313
You guys ever had an issue where you referenced UnityEngine.dll from a compiled managed library, then when building the player and running a given method it complain about a given Unity.CoreModule class?
I'm not getting errors on the editor, but when building my application and creating a NativeArray with UnsafeUtility, I'm getting this error:
System.TypeLoadException: Could not resolve type with token 0100008b (from typeref, class/assembly Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null)
Strangely, every time I reference a UnityEngine.dll from a managed library, the version stays 0.0.0.0
In the editor, UnityEngine.dll has all the separate modules combined, but for builds, the code is separated into modules like UnityEngine.CoreModule and the build only includes the modules that are used by the game.
So you should reference UnityEngine.CoreModule instead, or whichever module has what you need.
Unity dll's are always version 0.0.0.0. This ensures forwards and backwards compatibility for 3rd party dll's
But if I need to add ScriptableObject and UnsafeUtility for instance, the compiler will complain that both DLLs share some methods
In this case, UnityEngine.dll and UnityEngine.CoreModule.dll
I had no issues previously by using UnityEngine.dll reference, only this UnsafeUtility method is throwing errors
Oh, just realized the player UnityEngine.dll is different and does not have the duplicated methods
Lemme see if that fixes the issue
Does UnityEngine.CoreModule.dll not have all the types you need?
Not all. But I've already referenced all needed modules on my solution. Lemme see if that works
Same error, even when referencing UnityEngine.CoreModule instead of UnityEngine.dll
Not happening on the editor, only on runtime
Do you have any code stripping enabled?
oof?
I mean, not sure what is up
what should i do if i cant tell if a problem im having is because something is broken or because the set up of my game is just poorly set up? is there anything even to do? is it okay if it just works even if in a jank way on the back end?
@icy smelt
https://docs.unity3d.com/ScriptReference/Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.html
It becomes available by defining the ENABLE_UNITY_COLLECTIONS_CHECKS symbol.
๐ค
If this is the reason, then the define symbol would have to be added to the Player Settings in the project before building.
Same result
What Unity version are you testing this on?
2019.4.40f1
This is related:
https://forum.unity.com/threads/cant-get-atomicsafetyhandle-to-work-outside-editor-environment.1248019/
Oh
But I imagine ENABLE_UNITY_COLLECTIONS_CHECKS is only true in the editor
I'll have to think about how to do that since all my code is precompiled into libraries. So I can't use such conditional (unless I create duplicated methods which should take a while to implement)
Indeed, by removing the safety checking entirely, it works perfectly outside the editor
What is the best way to use ProfilerMarker? Can I define an array of profiler marker (native array) and use it in different jobs?
Tks @sage radish
I've got an interesting question, whats your setup? What tools do you use for coding/deploying/maintaining your game? Also, as someone who didn't come from a CS background, what are some useful things I should look into when it comes to games? (For example I just started learning database stuff recently)
Probably better suited for #๐ปโcode-beginner, but.. Visual Studio, obviously. The rest of your question is far too broad - there are hundreds of good libraries/technologies for everything you can imagine. Networking, databases, de/serialization, compression, audio, art, particle effects, advertising, stores and IAP, platform management (apple/google/steam/whatever).
it depends on the game & team
can anyone help me fix this
the tools you use 10 years down the road may be useless to you while you are only 2 years into it all. You might miss on some key insights for half your career and know more about others that anyone. There is no standard toolset that suits everyone's journey/needs
missing a using statement or assembly reference
do you know what the using statement would be ?
the namespace that the InventoryItem class is part of
Does anyone here do memory alignment for faster performance?
sorry to sound stupid but where would this be?
I meant more so on the libraries side or what services you use, in my time working in games so far I noticed that the teams I've worked with barely used any libraries at all
I'm asking something more like "what's your go-to tech stack" essentially
there isn't one. particularly in games there are only very few common problems that can be solved generically, most things quickly need custom implementations. For small projects you can get away with libraries, for larger ones a library or framework often gets in the way of the design for no good reason. This is even true for big frameworks like unity/godot/ue, they arguably don't really help in making a good game (they just take care of a few things typically required by a small to medium sized, non-cutting-edge project), they provides the bare fundamentals on top of which you build your custom libraries/tools.
as a general strategy for a company it can make sense to build most parts themselves to give them more opportunity to build something unique, even if the particular tech isn't immediately visible, the process and mindset of it are doing the work regardless.
Also libraries introduce a maintenance hazard, if it isn't supported by a reliable entity, support could just go away and you're stuck with maintaining it yourself, which in the case of a generic library can be a lot of work and quite low ROI if your project doesn't need all that much generality. Often its more efficient to build the specific thing you need yourself than rely on an opulent solution that also deals with 10 other things and has a more complicated API everyone has to learn.
So dialogue is pretty common in modern games, and so are cinematics, and for those things I'd personally not want to start with scratch given cinemachine is pretty comprehensive and there's a handful of interesting solutions for dialogue you can just grab for free
Or like, why bother writing your own networking solution from scratch unless you're just learning how it works
I think regardless when you're working in a team you're gonna have to learn how to read someone else's stuff anyways, so if you had something that could fill a need of your game that has documentation + has had the time to mature into a usable tool, it's probably best suited for big problems like those. I've also just found it a tad interesting how a lot of games focus on combat and have healthbars but those aren't "out of the box" things in unity, whereas unreal has a lot more out of the box
And then of course there's the libraries you write yourself that are transferrable, like player controllers or damage systems or AI (which, behaviour trees are extremely useful and making one from scratch mid prod sounds like a nightmare but they aren't in unity by default)
ARM what? ARM Linux?
no
Unity doesn't support Linux on ARM as a build target afaik
There is no plan to support arm? 80 core arm servers costs the same as 6 core x86
Can anyone point me in the right direction? I'm trying to rotate by using quaternions, and it works fine individually for each axis, but when combined together I get this sort of movement instead of a smooth up/down left/right:
here is the code:
private void Mouse_performed(InputAction.CallbackContext context)
{
Vector2 delta = context.ReadValue<Vector2>();
transform.rotation *= Quaternion.AngleAxis(delta.x, Vector3.up);
transform.rotation *= Quaternion.AngleAxis(delta.y, transform.right);
}```
again, for each of those rotations it works fine by itself. But if I do both like that, I cannot look up/down or left/right in a straight line.
FPS rotation is typically relegated to two different objects for a reason.
ah it is?
Yes go follow any fps tutorial
The camera is typically a child of the player and only rotates on the local x axis
Meanwhile the player itself only rotates on the y axis
i generally do not like following tutorials. Also I find some computers/monitors get choppiness from cameras being children
more importantly I'd say is that generally you don't just apply delta directly, you accumulate it into variables and use those to construct the rotation
you can bypass the hole child thing fine if you do it that way, though you still have to understand how to construct rotations
This is not #archived-code-advanced material
If you can't figure out the location of the class then you're definitely just copy-pasting everything
Every person with a basic bit of c# knowledge would know that if a class exists in a namespace, you will need to reference the namespace
Plus the IDE even suggests it if there is applicable namespace
Unsafe.As<char[], string>(ref chars) = _str;
Trying to reinterpret my string as a char[]. Basically it skips the first 2 indexes. _str[2] becomes char[0]
why is this happening?
or am I just using it wrong?
Managed arrays are more than just raw pointers. Span is closer to what you're expecting. Assuming you're using a recent Unity version, you can do _str.AsSpan() and it will return a ReadOnlySpan<char>. That's a wrapper around the actual memory where the string is. C# strings are immutable, so it's only read only.
Okay great. How can I then get that into bytes?
without allocating anything new other than the initial pre-allocated byte array
MemoryMarshal can reinterpret Spans. AsBytes is what you want.
Thanks
is there a way to read the stdout of a static lib you're using as a plugin - directly from unity?
I have a script where I'd like to access my submeshes so I can determine which submesh I've hit with a raycast. This works fine when my model is marked as non static and read/Write is enabled. Once I enable static (more accurate is 'batching static') I get an error "not allowed to acces triangles/indices on mesh 'combines mesh(...)' isReadable is false; read/write should be enabled in import settings". But all my objects in the scene are read/write enabled. Any tips on how I can get around this? Not setting it static is not the way I'd want to go. I'm thinking of adding a script to each model and store the sub meshes along with material id on each object but there must be an alternative I'm not aware of?
I got an issue I was wondering if someone could help me with. I need a shove in the right direction. I need to build a technical prototype that allows a person to create their own 3D level via a WebGL level creator, This could be with prepared assets already in the build or (if possible) also with custom 3D models uploaded by the player.
This then needs to be "playable", aka the player needs to be able to spawn into their own level and just walk around. Any other behaviours needed I can tackle myself down the road. I then want to be able to save this level to a webserver, So I can access it from another client (think schools or museums building their own scenarios to then present in several places).
I've been trying to wrap my brain around how to do this. First I couldn't really find many good resources on how to make a 3D level editor in Unity, giving the player position and rotation tools not too unfamiliar from those in the actual Unity Editor.
Another huge thing is how to save and load the data. I've managed to get my desired result on the loading end using assetbundles, but the way I understand it there is no way for me to build assetbundles or addressables during runtime, and so I am unable to give that power to the player. In other words whatever someone makes it would eventually need a Unity developer to put the assetbundle together in Unity. This is "workable" as it lowers cost seeing how a Unity developer would only need to be hired for a day here and there to put the bundles together, but it is not the most desirable solution.
Another way I thought of doing is using json and CreatePrimitives, but this severely limits what meshes I can work with.
I also considered using the Resource folder somehow, but haven't touched it much before so not sure what the full benefits or capabilities would be. I just know it's like a compressed set of assets.
TL;DR Trying to build a WebGL 3D level editor that saves the level to a webserver which can then be loaded in from a separate WebGL client but I am stupid. Any pointers in the right direction appreciated.
I am adding an Angle to my Ellipses with an angle value between -1 and 1 (which corresponds to -45 and 45 degrees) but this is only offsetting the Y value, I also need to shorten the length of the axis I am rotating to keep the ellipse the same shape. what factor would this be?
a more general question to unity's way of coding. Perhaps someone knows the answer.
For floating-point numeric values, most unity api methods use, well, the float-value type or another name would be single.
This gives us a good range of precision of roughly 6-9 digits.
Why doesnt unity use double?
Double has, well, double the blocked size on the heap as float does. If we call a script which has 50 blocked floats on the heap we are at 200 bytes, with double we were at 400. But double is much more precise with ~ 15-17 digits.
Is it as simple as "we dont need such a high precision so single/float is just enough and we save memory" or is there something more to it? It is not important to know, but rather a question i am just interested in. Sorry if this is the wrong channel, but since it is very specific to coding and mostly irrellevant for beginners i figured i'd ask here :)
I'm pretty sure it was just a memory thing in the past.
Mono used to turns all those floats into doubles when doing math operations so there was no performance benefit to using floats.
(This may have changed since Unity 2021.2).
Alright that is funny, thanks for the reply <3
The answer is as simple as 2 32 bit floats can be loaded into 1 64 bit register and worked upon
we are using async/await for a lot of our stuff, especially loading adressables. when pulling in some catalogs I get a frame of 2500ms, but the profiler is not very helpful with the stacktrace
it just shows MoveNext for the parent of JsonConvert.DeserializeObject
I wonder if this can be improved somehow
the stacktraces from Debug.Log are usually more helpful
seems to do some different unwinding
would using another synchronization context implementation help here
wasn't there some third party library that implemented a different task runner and some other helpers to wrap unitys own handles like AsyncOp
unitask?
yes and in 2023.1 Unity has its own thing called Awaitable https://docs.unity3d.com/2023.1/Documentation/ScriptReference/Awaitable.html
following a tutorial
Then the tutorial should point you to the file
Tip: don't start with Unity as your first project
Disagree I did
Cool, still not a good idea
Unity has its own learning curve and it's not a good starting point to learn c# as a whole
What do you suggest?
To not use Unity as your first project
Ok
I think it's fine to, but it's definitely easy to get lost in how things work due to the Unity framework/engine and how things work because of the C# language and CLR. If you're aware that there's a distinction and able to be observant and reframe your understanding of things from time to time (which you'll need regardless of where you start or what you do), you can be fine starting with it
when I first started with Unity I pretty much used it strictly as graphical console, with a MonoBehaviour in the scene as the app entry point and from there writing effectively a console application, slowly incorporating some Unity features to display things in the scene
I guess it depends on personal motivation. For me I found it easier to learn in unity. Was more fun and practical for me
Sure, but judging by messages in #๐ปโcode-beginner the majority of newcomers in lack any sort of experience altogether, and wont be able to figure out what they are doing because they juggle with two new concepts they don't understand at all
For a more experienced programmer trying c# and Unity I'm sure it is easier to adapt, but you will still miss out on a lot of fundamentals of c# if you decide to start with Unity
That's true
That's why I'm always daying to just start with c# and get those basics down. It allows you to understand how actual c# works, and also gives you the opportunity to understand why Unity does it different
can you elaborate more?
but this seems more like, a projection?
you are viewing from some angle and you have an actual length, just project it on the axes of your viewing and you should get what you want (key terms: axis projection, dot-product)
Could anyone help me with preprocessor variables real quick ?
My library supports .NetStandard 2.1 and is compatible with newever unity versions.
However my libray also features c#11 API stuff like generic attributes Attribute<T...>.
Unity does only support c#8.
Can i still use the library with unity as long as i dont use the attributes ? Or what happens in that case ?
Wrapping that stuff into preprocessor variables wont help since its a nuget.
Any help appreciated
it's to create a path for an object to orbit. it's not very important but basically to add an angle to the path I simply add a value for the y position. this would be the front view if you tilt it on the x Axis. since I'm adding a y offset it gets stretched so I would have to compensate for that by shortening the x position by a certain amount
since 0 degrees is 0 and 45 degrees is 1, I tried remapping a 0-1 scale to a scale of 1-0.70708 which seems to be the factor of how much shorter it needs to be at 45 degrees but this didn't work. maybe I remapped it wrong
you'd have to share some code but this doesn't seem like the best way to do what you want
it seems I am overcomplicating things... I can simply rotate the empty object I am orbiting around...
Probably better to create a transformation matrix (Matrix4x4) and multiply all the points in your ellipse with that matrix to transform it
or that, yes
Any help here ? Can i use a library/nuget with c#11 features in unity when i dont make use of those features ?
it s to create a path for an object to
How do you prefer to implement it?
There are different type of buildings. It does not matter, in my example, it is building but can be everything like weapon, etc.
They have same components as well as specific ones.
To create them, they need level number and definition data. Their components are initialized by definition data
For each building type, there is a corresponding definition type.
Do you favor to create factory class for each building type?
or one factory for all of them. Create method takes Int level and base definition data. Then, each building cast base definition data to specific definition inside its own class.
another approach
passing level and building ID instead of its definition to factory class, then getting data by id in the building classes
Hi there im trying to parse this json but I dont know what the class look like ```json
{"-NM60tD29b7Bp7E21h5v":{"guid":"8aa219ff-0111-4b9c-8c98-675ea08171cd","levelData":"banana"},"-NM61TrzwR2csc_07MMK":{"guid":"c5ab1f87-bae8-493e-ae96-39bced732c8b","levelData":"banana"},"-NM62unW9banfKbcwJ1W":{"guid":"3af2034e-d538-4c1f-89b4-4a8fadf51f02","levelData":"banana"},"-NM65Ck5Cz1PzqN3k4ex":{"guid":"ccbd9172-8f78-476c-8118-31264aad0540","levelData":"banana"}}
Just looks like a Dictionary<string, SomeObject> where SomeObject contains a string guid and string levelData @blissful peak
Not something that can be parsed with UnityEngine.JsonUtility though
Thank you for your answer. Have fiddled around with the JsonUtility with no success. Do you recommend a direction that I can continue in!:)
Yep, use a different JSON parser such as Newtonsoft JSON
awesome, cheers
Got it to work within minutes. Thanks a bunch!
Do you guys know about any library/template to help migrating a codebase to use IEnumerators (so I can use Coroutines with it)?
I don't want to break compatibility with my existing code, and the way I think about doing it would require adding lots of #ifs into the code
May I DM you
@sly grove Reasonable lol Iโll say it here, I wanted to thank you for the help youโve given me over the last year. Tomorrow is my thesis proposal presentation and I absolutely would not have been at the stage Im at without your help. I appreciate it
for future reference you can DM me stuff like that, just not Unity help requests ๐คฃ
Ah some people donโt like it whatsoever Iโd rather make sure
But yeah thanks lol
Does anyone know how to add/modify script code through editor script only for when build game (assembly) without changing project scripts?
What are you trying to do
like what would this system be used for
when the project is building I want to add variables referencing other scripts, but only for when it's a build
Why only for a build?
It's possible?
Not really
but what scripts do you want to reference
and why only for a build
oh there is an alternative
you can use preprocessors
like #if UNITY_EDITOR I think
then #else
for anything else
but you can't inject code along the build pipeline unless you had Unity's source code and changed it to allow for that
I'll try to explain but I'm terrible at that hehe, I can reference some variables, the variables I want, through the editor side I want to remove the unused variables (because there are many) modifying the script through System.IO but only when for build, when in the editor I want to keep them in case I use them
Youโre right, itโs terrible explanation
If you can build it into managed dll then you would be able to use it in Unity. Itโs still .netstandard after all
So if I take all of my c# framework code, compile it into a DLL, does it then become native machine code? Or is it still going to be interpreted?
Managed dll contains IL code
IL2CPP converts IL to CPP so
Ok great
I have a ton of models to import (fbx files) with materials. Whenever I bring them into Unity, the smoothness value is automatically set to 60. If I want it to be 0, is there a script I can use that automatically does that for me on import, so that I don't have to extract each individual material to edit the each value manually? (I am using URP)
You could look into https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html
using UnityEngine;
using UnityEditor;
using UnityEditor.AssetImporters;
public class MaterialSmoothnessPostprocessorURP : AssetPostprocessor
{
void OnPreprocessModel()
{
ModelImporter modelImporter = assetImporter as ModelImporter;
modelImporter.materialImportMode = ModelImporterMaterialImportMode.ImportViaMaterialDescription;
modelImporter.materialName = ModelImporterMaterialName.BasedOnMaterialName;
modelImporter.materialSearch = ModelImporterMaterialSearch.RecursiveUp;
modelImporter.materialLocation = ModelImporterMaterialLocation.InPrefab;
}
void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] animations)
{
material.SetFloat(Shader.PropertyToID("Smoothness"), 0f);
}
}
This was my best shot lol
Didn't work, must be doing something wrong
๐ค
The property in shader is not "Smoothness", it's "_Smoothness" I think
lol that worked, thanks
I do get the following warning when I reimport assets now though:
Importer(FBXImporter) generated inconsistent result for asset(guid:40320499d63dd344e9a9e696a1209e8f) "Assets/Temp/Visuals/Models/FBX/room_project.fbx"
Did a reimport all. Seems to have gone away.
lol oops, posted that in wrong chat
Hi everybody, I have a problem with bones of a character when I use them inside an animation, then I can't modify their position or rotation anymore through code, it's simply ignored, even if the current animation doesn't use the blendshape... Why is it not working anymore ?
If the bones are never used by animation, I can change them in the update method
I have a very hard problem with reversing an angle in a code (https://paste.mod.gg/ghgmpjllfqvn/0), https://gyazo.com/85052e86f74ccd0d867bcaa08d8fbc92, see this gif for the issue, my character can move in the up left diagonal and the animations change properly, but when I walk in reverse, the wrong animations play in relation to the angle, i tried numerous stuff to reverse the angle direction somehow but I failed ๐ฆ
A tool for sharing your source code with the world!
Basically I don't need to 'reverse' the angle variable, I just need to find a way to offset the animation in the other direction somehow when walking in reverse.
Because otherwise the controls would be inverted.
Sounds like you should implement this purely with vectors and quaternions and do away with all that messy trigonometry
Can someone give me some direction to make my player point the same direction as my camera? I have a character that will eventually be a spider, so it walks on walls and ceilings. I'm using this code to set the rotation right now. I just changed the forward to be calculated with the camera's right rather than the object's own transform. Now it works until it gets about 90 degrees then it seems to flip and points toward the camera instead of the same direction.
//Vector3 forward = Vector3.Cross(transform.right, up);
Vector3 up = transform.position - (Vector3)closestPoint;
Vector3 forward = Vector3.Cross(sd.camera.right, up);
rigidbody.MoveRotation(Quaternion.LookRotation(forward, up));
Perhaps I could compare the dot product of the up vector with Vector3.down and if the spider is more upside down then I flip the forward to use -camera.right instead.
I'll try that, but it seems like there might be a neater mathmatical way to do it.
I fixed it because I had the revelation when I wrote the question lol
A tool for sharing your source code with the world!
Like this
gotta clean it up though
My solution didn't work. It fixed one case but broke another.
This is why I didn't go in 3d game making, the maths for this is a nightmare >_<
lol just rotations. I can deal with translation and scale.
I think I might have figured it out. I projected the camera's forward onto the same plane that I'm rotating the player on and it seems to work for every angle I've tried.
Vector3 up = transform.position - (Vector3)closestPoint;
Vector3 forward = Vector3.ProjectOnPlane(sd.camera.forward, up);
rigidbody.MoveRotation(Quaternion.LookRotation(forward, up));
I love it when I start typing a method name I want to use and it actually exists.
https://gyazo.com/95e3571398482e32da1980e4a24d92f0 anyone have any idea how to fix this? I have the animations set to trigger based on mouse angle, but there is a specific point between the angles where it won't know exactly which angle it is (I already rounded it), I set the camera position to the player in an OnUpdate event, I also tried making it a child of the player character in the scene and nothing worked (I think it's the camera position that is doing this if I'm not wrong).
When the angle changes, it jumps a keyframe in the next animation set and this bug has been plagueing me for weeks, if I put the player script that handles the animation frames in a FixedUpdate, this still happens but instead of increasing the animation speed, it jitters, it may be because Unity doesn't like doing floaty movement directions.
so... i found on a forum that in TMPro you can add padding to a mark tag like this... <mark=#ff800080 padding="-10,-10,-10,-10">... however... it's not documented anywhere, and i cant find how it works for the life of me even reading thru Tmpro in my package cache... so like.. does anyone know where to find all the "actual" like.. modifiers you can use with mark tags, or where marks are rendered in source code?
if it works... you'd think it would be mentioned like... https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/manual/RichTextMark.html here?
Your mark tag is working for me. Weird.
I'm on TextMeshPro v3.0.6
Does someone know what happens in C# memory when I do this?
public delegate float TargetInput(GameObject actor, GameObject target);
static TargetInput TI_DistanceToTarget(float maxDist) => (actor,target) => {
var dist = (target.transform.position - actor.transform.position).magnitude;
return Clamp(dist/maxDist);
};
Like, if I make 10 delegates with maxDist (1..10), what does that mean in terms of memory?
The compiler generates a class to store the maxDist value and the anonymous function in and creates an instance of it in the TI_DistanceToTarget method.
or 10 delegates all with maxDist = 1.
If I make 1000 delegates all with the same maxDist, will the compiler generate 1000 classes?
The compiler only generates one type for this method, but replaces the method body with just creating an instance of that type.
This code gets compiled into something like:
public delegate float TargetInput(GameObject actor, GameObject target);
[CompilerGenerated]
private sealed class <>c__DisplayClass1_0
{
public float maxDist;
internal float <TI_DistanceToTarget>b__0(GameObject actor, GameObject target)
{
float num = (target.transform.position - actor.transform.position).magnitude;
return Clamp(num / maxDist);
}
}
private static TargetInput TI_DistanceToTarget(float maxDist)
{
<>c__DisplayClass1_0 <>c__DisplayClass1_ = new <>c__DisplayClass1_0();
<>c__DisplayClass1_.maxDist = maxDist;
return new TargetInput(<>c__DisplayClass1_.<TI_DistanceToTarget>b__0);
}
(the compiler uses characters like <> in generated types, because you're not allowed to use those characters for naming in C#, but the compiler can, so it avoids any potential conflicts with existing types)
very cool, my slow brain is processing atm
is it right to say then that for every field of type TargetInput , maxDist is occupying memory in there?
Here's a cleaned up version which is a little easier to read:
public delegate float TargetInput(GameObject actor, GameObject target);
[CompilerGenerated]
private sealed class DisplayClass
{
public float maxDist;
internal float TI_DistanceToTarget(GameObject actor, GameObject target)
{
float dist = (target.transform.position - actor.transform.position).magnitude;
return Clamp(dist/maxDist);
}
}
private static TargetInput TI_DistanceToTarget(float maxDist)
{
var displayClass = new DisplayClass();
displayClass.maxDist = maxDist;
return displayClass.TI_DistanceToTarget;
}
Yeah itโs just totally undocumented and Iโd like to know if there are any other keywords like โpaddingโ that work
I canโt find the source code where you could find any other undocumented keywords for Tmp
No, that depends on what the TargetInput is assigned to. This is just showing a specific example of what happens if you assign it to a lambda/anonymous function that captures an outside variable.
the return of this:
private static TargetInput TI_DistanceToTarget(float maxDist)
{
var displayClass = new DisplayClass();
displayClass.maxDist = maxDist;
return displayClass.TI_DistanceToTarget;
}
what is that? a reference or value type?
It's returning a reference to the TI_DistanceToTarget method of the DisplayClass instance that was just created.
and what about maxDist? how is that referenced?
It can't really be more clear than the example I gave you. It's creating an instance of an object that has a field where the maxDist is stored. That object also has a method that references that field in its calculation. That's the method that's being returned here. The method for that specific instance that has that specific maxDist assigned to it.
It's a workaround because methods can't have state tied to them, but objects can. So it's creating an object to hold the state and putting the method in that object.
Cool, I think I get it now. It (i) wraps method + maxDist in a class, (ii) returns method that in it references maxDist.
Every call to TI_DistanceToTarget() creates a new DisplayClass() object
Thx for the help ^^
Does someone know why the logic isnt working in this script? I want to do the AddMoney() Function on the time based on the InputfieldValue, when the Value is low, the time should be low also and when high then high (CheckChance Function). The Problem is, that it is constantly calling the AddMoney Function after the Time has passed. I want it for example when it calculates 10 Seconds, then after 10 Seconds it is calling the AddMoney Function ONCE, then after 10 seconds again and so on
do not crosspost
sry
i have multiplayergame with relay and lobby, problem is when trying to launch game when all in lobby with line of code "string relayCode = await TestRelay.Instance.CreateRelay();" it says NullReferenceException: Object reference not set to an instance of an object
LobbyManager.StartGame () (at Assets/LobbyTutorial/Scripts/LobbyManager.cs:385) and i have the button dragged in the right place it says in debugging that the TestRelay.Instance is null, any suggestion how to solve ?
should've left it in #๐ปโcode-beginner tbh
#๐ปโcode-beginner post your code
Is there a difference between:
1๏ธโฃ applying an acceleration to a rigidbody using ForceMode.Acceleration
2๏ธโฃ taking the same acceleration from 1๏ธโฃ, multiplying by Time.deltaTime, and applying it using ForceMode.VelocityChange
Naively, these two things seem like they'd be identical, but I don't know if the physics system splits the physics frame into smaller timeslices for stuff like collisions, drag calculation, etc. If it did the latter, than you could imagine there being a subtle but nonzero difference between the two.
they're the same except it's Time.fixedDeltaTime not deltaTime
Likewise:
rb.AddForce(force, ForceMode.Impulse);
// is the same as
rb.AddForce(force / rb.mass, ForceMode.VelocityChange);```
and
rb.AddForce(force, ForceMode.Force); // which is the default mode
// is the same as
rb.AddForce((force * Time.deltaTime) / rb.mass, ForceMode.VelocityChange);```
Awesome, thanks.
I tend to use Time.deltaTime everywhere since it gets set to Time.fixedDeltaTime when you're in the FixedUpdate cycle
true but occasionally you are doing things related to physics when you're not, I tend to make a habit of always using FixedDeltaTime. Though it's rare.
My usual example is doing a trajectory simulation for rendering a projectile path or something
Yeah, makes sense. Like if you were doing prediction and you had no idea where your code was getting called from, it's better to be explicit
What happens if multiple asset plugins use BuildPlayerWindow.RegisterBuildPlayerHandler? Will one override the other's 'RegisterBuildPlayerHandler'?
i think they all get executed
i would just make test case to know for sure
toss some logging in see if they all get called, and see what the final options end up as
anyone familiar with photon pun 2 here?
Tried to add IsMine to my player's movement script but it breaks the character. Can anyone tell why?
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.
This is my movement script
Player stays in falling idle animation and console says this:
I think you need investigate this:
view = GetComponent<PhotonView>(); it is null in your code. so thats why everything that in code is bellow will not work. like animations and etc.
so your update function is not running normaly
so either the script does not exists on same game object as MovementCharacterController.
This just build and not call Test();, what I'm missing?
static void Init() {
BuildPlayerWindow.RegisterBuildPlayerHandler(
new System.Action<BuildPlayerOptions>(buildPlayerOptions => {
Test();
BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(buildPlayerOptions);
}));
}
static void Test() {
Debug.Log("Success");
}
weird syntax
BuildPlayerWindow.RegisterBuildPlayerHandler(options => {
Test();
return BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(options);
});
also would make sure InitializeOnLoadMethod is doing what you want would log in that method as well
I debugged Init and it's working but it skips any method or even debugs and goes straight to build, only methods and debugs after 'BuildPlayerWindow.DefaultBuildMethods.BuildPlayer()' work
strange, at work i have used BuildPlayerWindow.RegisterBuildPlayerHandler a few times fine
I was trying that too but it also doesn't work:
static void Init() {
BuildPlayerWindow.RegisterBuildPlayerHandler(Test);
}
static void Test(BuildPlayerOptions options) {
Debug.Log("Success");
BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(options);
}
[InitializeOnLoad]
public class BuildStepRegister {
static BuildStepRegister() {
BuildPlayerWindow.RegisterBuildPlayerHandler(BuildBundlesAndPlayer);
}
private static void BuildBundlesAndPlayer(BuildPlayerOptions options) {
BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(options);
}
}
i removed all the code that is not relevent for you so it does nothing but this is how i have always done these
It's the same code I just sent, Debug.Log("Success"); the one I sent should work? Or am I doing it the wrong way?
Hello. I have a basic-ish question. Can I implement Systems without ECS? Or How can I achive something like this? https://blog.littlepolygon.com/posts/bullets/
I've worked with Jobs before, but never with Systems
and it seems more efficient than my Job https://pastebin.pl/view/24503960
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
is there any way to convert a string field to c# code on awake for example
i want to use a string field to input a math equation
then on awake set it up as a function to use in runnable code
Parse the string and decompose that into a bunch of Funcs that target prebuilt methods. It's not ideal but that's your only reasonable option
I believe the Roslyn compiler is capable of doing just that
Alternatively, you can look into adding lua support for ease of scripting
The article you linked does exactly that. I think he just forgot to add a MonoBehaviour to his bullet system and that might be confusing you.
https://www.youtube.com/playlist?list=PLDpv2FF85TOp2KpIGcrxXY1POzfYLGWIb I've been following this tutorial on Utility AI, and one thing got me confused: it does actions as scriptable objects, and puts action score and destination inside the action. In my understanding that makes every action bound to a single NPC, unless I'm missing something. Although I don't know what. I've used them for a long time, and they've always behaved this way.
So I imagine this will be easy, just wanted to talk through it first. I have a low poly object, and I have been placing prefabs along the main edges(aka the change from one side to the other is sharp/not flat). I am not super familiar how mesh data is stored(a video on this would be amazing) nor how to tell if one side of an edge is at enough of an angle from the other to know to place a prefab at the edge though I know this information is used in shaders often.
what edges???
Ah(terminology miss match I guess). Vertex? The line between two dots.
ah for some reason I have thought of the sides of a road or something
the angle of the edge between what? the world up direction and the edges normal?
Ah yeah man, you are speaing greek to me.
.
/
. __ .
So that is a tri, and the lines between the dots. Each tri connects to others. So if the change of tris facing I guess(so normal?) direct is great enough then place the prefab on that line.
you mean the angles inside the triangle?
Maybe an image of what I am doing will help more. I don't know the terminology.
btw. the normal vector is the vector that is pointing upwards on a vertex
So I am placing those line prefabs on the sharp edges of each face. Note that I didn't place them on the internal lines of the faces as the angle(or normals between the two tris) isn't great enough and just looks like a flat surface.
so a vertex is a tri?
no a triangle is made out of vertecies
th vertecies are the 3 points
Ah a normal is just that vector off of a tri. What is the line between two vertecies called?
edge was correct my brain wasn't functioning properly, and no the normals are the "up" directions of the vertecies
the interpolator (a stage in the shader) blends between the normals of the vertecies, thats how you get that smooth shading
What is the up direction of the triangle?
or would there be a better way of determining the angle of the edge?
its an interpolated normal, but essentially its also just the normal, but usually when we say normal we mean the one from the vertecies
anyway coming to your question you can get a list of the normals inside the mesh if the normals have changed the direction, the surface isn't flat anymore
Did you set the transform as boneโs parent first?
Yes the boneโs transform.parent
Can you show the related code?
I can say with your help and the very weird(all be it pretty flawed) help of AI I just made a script in about 2 hours that is going to save me countless hours of work.
hey everyone, I have a very strange issue, vsync is making lag in the game so I deactivated vsync from every single place possible, however after 5-10 minutes of gameplay while profiling the game, i noticed vsync turning on by itself for a few seconds making an insane lag and then turning it self off and then game runs as normal, what is going on?
I am not able to find anything on the internet regarding this issue, I am trying to fix it for 4 days now
This looks weird, I donโt see the transform itself, the one you running the bindpose code
Tried to make the script assign the gameobject/movementcharactercontroller script automatically once the player prefab has spawned in the scene. But I'm getting a few errors here, can anyone tell me why?
I think you are missing ()
Where exactly
MovementCharacterController is not a property of GameObject. The couple of built-in convenience shorthands for components are the exception
after the movementCharacter...
However this script, once fixed, is not likely to do what you want it to do.
HelpUI presumably sits in the scene permanently and the character controller is then spawned in later, right?
Its basically a UI script and I just want it to automatically assign to the player prefab containing the movementcharactercontroller script once the player has been spawned...
Yep
Right. So the Start method of the UI script is run before the spawn happens.
ye
So even if fixed, your UI script will always fail to find the player.
Hmm
Additionally you're running an expensive search twice - throwing the first result away.
Generally FindWithTag should be your last resort - or an early one if you're writing Unity tutorials for some reason.
Reason why I wanted it was because I couldn't make a proper multiplayer since two player prefabs containing the ui elements broke on of them two.
The simplest solution for this is to turn the call order around - so it matches the spawn order.
So like even without multiplayer just 2 players in a scene broke one of em and reason was because of the components of one of them failed to assign the right scripts
Uh I thought this would just be adding a few lines of code especially since this isn't my script and because I'm mostly just a game designer.
Say you have a Player component attached to your spawned player object and a Game component sitting permanently in the scene. Using approximately the same methodology you could then go:
class Player
...
private void Start ()
{
if (FindObjecOfType<Game> () is Game game)
{
game.Register (this);
}
...
With the Game type then implementing a Register method ofc.
Alternatively you can do direct assignment where-ever you're doing the player spawn.
Like:
...
Player player = Instantiate (playerPrefab, position, rotation).GetComponent<Player> ();
game.Register (player);
...
Turning an existing game into a multiplayer experience is going to require a good base understanding of the programming concepts making up the original game. If you want to solo that mission then some learning is in order ๐
Thanks a lot buddy!
It's actually a game that doesn't exist yet. Online functions are the majority of the game and I'm now trying to do those internal things before working on levels and stuff.
Hello I have a question I would like to ask, Now this might be a stupid question but I couldn't find anything. I would like to render a specific Object to one of the cameras but not to the others, now usually I can just assign the layers but how can I achieve the same with indirect gpu instanced objects
That's probably a question better served in #archived-shaders
if you say so
It seems to be the closest to a rendering section here ๐คท
How do I make StateMachineBehaviours receivers of corresponding animation events? Just tried adding methods with the same name to the SMBehs but still get an error saying that my animation event has no receivers
Thanks! I'll try this as soon as I get home
your mesh data itself is offset from its local origin
This will only happen if some code/script is doing it
or your mesh is offset
etc
it doesn't just happen
Also you need to just press z
because you probably have tool handle pivot set to Center
instead of Pivot
this thing
that says Center
Change to Pivot
did you fix your tool handle position thing
before all this discussion
is it set to Pivot?
skinned mesh moves vertices based on bones positions
so maybe your bone objects are in a different place
it's the top level bone in the model's armature/rig
or whatever Transform you assign to it will represent that bone at least
Given an N sided dice and M dice throws, whats the fastest way I can generate an N sized array with the value of each throw:
For example, 6 sided dice thrown 3 times: [2, 1, 4]
The first obvious approach is just loop over an N sized array and randomly generate a value from 1-N, but I'm not sure if this is the fastest.
Another approach I thought of is to do it in groups. Say you have a 6 sided dice thrown 3 times, you would have 6 groups which can be represented as an array of size 6 and then distribute the number of throws, 3, into those 6 groups:
[1, 0, 2, 0, 0, 0]
So here there was 1 throw of value 1 and 2 throws of value 3. Then I can generate a final array of [1,3,3] and scramble it.
The problem is I'm not sure how to distribute the number of throws across the group such that it represents the correct distribution for fair dice throw. (where each value has equal probability to show up). I also don't know if the scrambling makes this slower or if that messes up the probability distribution either.
Technically for my use case, the scramble isn't required but if a fast method is able to do so that would be nice.
You get an array of random values between 1-6 and then take a span of a random offset with N length
does that maintain the right distribution tho?
No idea
im fairly sure it doesnt
lets say N = 100, ur first span is on average 50, second span is then on average 25 (span of left over space, 50) etc...
?? if you are suggesting creating an array of random values between 1-6 then you didn't understand my question since that was literally the first thing i mentioned
Im perfoming a very large number of dice throws like 1000000 and I want to get an array of all the values. Obviously calling random 10000000 times is gonna be slow so I was wondering if there was a faster way to do it
the job system might be good for that. Should be pretty easy to make a job to roll a dice 1000000 times parallelised
do you think there is an algorithmically faster method, cause I understand that you can just multithread it to cut down on time superficially
I don't see how anything could be faster than just generating n random numbers?
You can parallelize it of course, (this also requires a number of random number generators equal to the number of trheads you use)
maybe I'm missing something about the question
same
I'm just wondering if there is anything that could be faster than just generating n random numbers. I already know I can parallelize it. I provided a second approach involving the groups which may be faster with less random calls. But like I mentioned that I don't know how to properly distribute the dice throws over the groups such that it maintains the correct distribution
I didn't really understand your second approach tbh
oh wait I think I get it
say you have 100 throws. You might end up with:
[21, 19, 24, 16, 20]
yeah exactly
But then you still need to ... randomly order them somehow?
It seems like you'll end up doing just as much work if not more in that process
also how do you actually generate this thing?
that was my question lmao
start with numThrows / numDieFaces then do +/- with standard deviations or something
it doesn't seem like it'd be evenly distributed
I guess one question is what is the actual requirement here
do you need them in the order they appeared
or do you just want to create a distribution
what do you mean by this?
Do you just need [21, 19, 24, 16, 20, 20] or do you need [1, 2, 6, 4, ....x1000]
ur second one
what are you doing with those random numbers
the first one was just a suggestion i had on how you could go about making the second, but obv its flawed :p
If im completely honest, im just wondering if there is a faster algorithm, so utterly nothing lol.
burst and jobs is probably the fastest you can get
I think if you actually need N random numbers, you will have to generate N random numbers at some point.
out of curiosity, if I said I needed the first what were you going to suggest?
yeah i figured as much thx for trying tho :p
Well I think there's a way to just generate convincing distributions easily.
maybe start with even distribution: [20, 20, 20, 20, 20, 20]
then do n iterations of perturbations
e.g.:
[20, 20, 20, 20, 20, 20]
[19, 20, 20, 20, 21, 20]
[19, 20, 20, 19, 22, 20]
[19, 19, 20, 19, 22, 21]
like pick one group to take move from and one group to move to
at random
do that n times
and you'll have some kind of random distribution
That n could be significantly less than the number of dice it's simulating
yeah I see what you are trying to do
but I'm not sure how big n would have to be compared to:
- number of groups
- number of "rolls"
for it to be convincing
you can imagine if you started with:
[1000, 1000, 1000, 1000, 1000, 1000]
obviously doing ONE iteration is not enough
nor is two
but at what point does it become "convincing"? WOuld you have to do 6000 iterations?
If so this isn't helpful ๐
yeah i got you xD
do you want a 7ms to do 1000000 numbers script that i've just made?
i'm very surprised it's so fast
Here it is anyway (I forgot to dispose of the array at the end)
sure why not, I was asking a hypothetical so it didnt really matter
Initializing a random for each thread and reusing them, should be faster.
Is there any way to make a gameobject more transparent without changing its materials?
Material/shader defines how the object is rendered so no i guess
welcome to code advanced my g
If your interested, I managed to find a really fast way to get the counts for the first array suggested. Its basically sampling a multinomial distribution: https://en.wikipedia.org/wiki/Multinomial_distribution. I essentially copied numpy's source implementation of it from here: https://numpy.org/doc/stable/reference/random/generated/numpy.random.multinomial.html
NavMeshMovement:IsMoving () (at Assets/uMMORPG/Scripts/MovementSystems/NavMeshMovement.cs:35)
Monster:EventMoveEnd () (at Assets/uMMORPG/Scripts/Monster.cs:136)
Monster:UpdateServer_MOVING () (at Assets/uMMORPG/Scripts/Monster.cs:272)
Monster:UpdateServer () (at Assets/uMMORPG/Scripts/Monster.cs:496)
Entity:Update () (at Assets/uMMORPG/Scripts/Entity.cs:190)```
If thats not what you were asking, I dont know what is. Of course you can set properties of material using Material.Set(type) instead of replacing the whole material. MaterialPropertyBlocks are also an option but they do break srp batching and works only with gpu instancing. In order to change how object is rendered, you must change the material properties/the material itself. Am I completely missunderstanding what you are asking?
Hey all, popping in with a question to see if I am missing something in the documentation. Is there any easy built in function to record and export a video in game for Unity? I see a lot of tools for devs to record in editor but I am looking to, for example, record a gif for mp4 to post to social media.
hello there, another bit of linq code that i wanna trim down
buttons.ForEach(x => x.gameObject.SetActive(false));
buttons.Where(x => x.name.Contains("Retry") || x.name.Contains("Menu")).ToList().ForEach(x => x.gameObject.SetActive(true));
//v2
buttons.ForEach(x => x.gameObject.SetActive(false));
var tempButtons = buttons.Where(x => x.name.Contains("Retry") || x.name.Contains("Menu"));
foreach (var b in tempButtons)
b.gameObject.SetActive(true);
is there any way i can do this without having to convert it to a list first?
edit: i managed to do that, but i wanted it in one line for funsies, is that possible?
i would just not do it with linq
fair assessment
like you are looping to check a condition and set it inactive or active
but you can just loop all buttons, and check that condition directly and pass it into SetActive
item.SetActive(item.name.Contains("Retry") || item.name.Contains("Menu")) for each iteration
foreach(var btn in buttons) {
btn.SetActive(btn.name.Contains("Retry") || btn.name.Contains("Menu"));
}
it seems like i like to overcomplicate these things ๐ thanks for the insight
I'm doing manual physics updates with Physics2D.Simulate so I can add an onPostPhysicsUpdate event for special corrections in a player. However, it looks like Unity's model of the Rigidbody2D is only updated on calls to Physics2D.Simulate. Does anyone know how I can trigger a refresh without progressing time?
assuming you are new to linq, find its pretty common when people learn a new tool to try it out everywhere till they get a feel when and where to use it. It's just part of learning
yeah i'd say im new to linq, i empathize with that
Nevermind. It doesn't seem to be related to my problem. Though it does seem like Unity updates the collider outlines in the editor like this.
How can i check if an area is inaccessible in a 2d tilemap based, i thought about using A* path finding but it would not be efficient as it would check for the whole border of the area, i thought about calculating inaccessible area and saving it but then if i implement comstruction or something changes in the game the calculation needs to be done each time.
What solutions do you suggest?
hello
I am calculating with Mathf, but it is very different from the result calculated with a calculator.
I don't know where the problem is, so I would like someone to help me.
I would like to see your code first. Mathf functions obviously should be mathematically correct so its most likely something wrong in the code. It could be something like lack of degrees to radians conversion when you are dealing with triconometric functions such as Mathf.Sin
This code
(((6377397f/(Mathf.Sqrt(1f-(0.006674f*Mathf.Sin(35.27476)*Mathf.Sin(35.27476)))))+104.601f)*Mathf.Cos(35.27476)*Mathf.Sin(137.0158))
The calculation result is -1679967, but it should be -3813048.
Can someone please tell me what is wrong?
Read my first answer carefully and then read the docs page for Mathf.Sin https://docs.unity3d.com/ScriptReference/Mathf.Sin.html
I made a terrible mistake.
It looks like I was doing the math without converting to radians.
Solved, thanks! !
Please dont advertise your questions on other channels, people that are interested will read that channel too
sorry.. deleted the question
How much memory does eg 10,000 empty script references take? Does it have any performance impact?
Like:
Public ScriptToReference s;
/// And more 9,999...
Each one takes 64 bits, or 8 bytes. So 80,000 bytes, or 80 kilobytes.
That many serialized fields will probably slow down Unity's serializer.
@sage radish
It's not even half an MB, so it doesn't affect performance basically, but it affects the editor through the Inspector because it's public? That? sorry for the beginner question
Yes. But also there is no good reason for having 10,000 fields in a class, so I hope this is just a hypothetical question.
I hope you are not trying to reinvent a list using million public fields ๐
Yes, just hypothetically, let's say several references in a script but in several instances, but 10,000 just to understand the impact in an absurd scenario
Not because the references don't necessarily refer to the same script, so I need to get the reference and use its methods and variables, references are added to the script through the editor