#archived-code-advanced
1 messages · Page 179 of 1
if you don't believe me, someone benchmarked it: https://youtu.be/Xd4UhJufTx4?t=182
Can I get some attention to this question? (Please answer it in the forums)
https://forum.unity.com/threads/how-does-a-net-6-dll-work-just-fine-in-unity.1259720/
if you don't use .net 6 specific api's it should just work
If anyone here has worked with FMOD before - I know that FMOD is generally designed to react to gameplay via parameters. But is there any way to do things in reverse; to allow code to respond to triggers within FMOD events?
For example, allowing a looping music section to finish before triggering a gameplay section.
Yes, it's definitely possible. I don't remember the details of the top of my head and I'm on mobile so I can't look it up too effectively right now. https://m.youtube.com/c/ScottGameSounds/videos has good FMOD tutorials. You should be able to listen for named markers (I think that's what FMOD calls them?) and ready in your unity code to that.
Awesome, I'll look into them!
So training neural networks is not so easy lol
But I have found a few bugs and squashed em
Here's the relevant FMOD docs: https://www.fmod.com/resources/documentation-unity?version=2.02&page=examples-timeline-callbacks.html
Hi folks...Is there a way to manage a window within unity, but outside of the main unity build window?
like if I wanted to drag game components outside of the main build window
i.e. a single game or app that can use multiple windows
I need some help calculating the rotation of my AI to activate a turn animation in a blend tree, I need to calculate the left turn to -1f, and the right turn to 1f. is there anyway I could do this?
?
you can write native code or plugin code to do this
Do you know what namespace I need to review? I am having trouble googling the information
uh
is this only for windows?
what's the objective?
The objective is to have multiple components that can be dragged outside of the main view space....so I can have the main game screen on one display, and helper components dragged off to other displays in windows.
I need to calculate the the angular velocity of a game object and convert them to a right and left float (-1f, 1f)
So if the game object turns right I will get a float of 1
And if it turns left I will get a float of negative 1
@regal olive https://docs.unity3d.com/ScriptReference/Vector3.SignedAngle.html
store previous frame forward, use this to compare with current
Unity itself does not support this kind of thing. You can however render to multiple displays and have some very basic controls over what camera renders to which display. There is no concept of multiple OS-level windows in unity.
Yeah I didn't think so, but I thought it was still worth the query. It would have saved me a lot of work.
theres an asset "full screen editor" they are doing os level hacking to render into a window
Hya. I'm running into some Vector math issues. I'm using Shadergraph, which leaves me without the usual way I'd do stuff (Quat.LookRotation etc) . I got two transforms, and I need to rotate transform A so its looking to transform B. Because I'm using shadergraph I need to calculate it "Raw"
I can calculate heading and direction easily. But I'm running into trouble to convert those to EulerAngles or Radians
which is what I need to rotate the object
So, the question: without using Quaternion functions and the like, how does one calculate the rotation degrees or radians a transform from a direction or heading vector3?
Why do you need euler angles to rotate the object?
Quaternion.LookDirection makes a quaternion pointing in your heading direction. Then you can just Quaternion.RotateTowards or Sleep to rotate it
I;m using Rotate About Axis nodes (working on a billboard shader)
Oh shaders?
Yeah shadergraph. So I need to manually convert a directional Vec3 to a rotational Vec3
Oh maybe #archived-shaders
I've tried for a few days there, channel is kinda slow / dead 🙂
and since it's kind of "basic" Vector math, I though I'd ask here
and, unfortunately my Google Fu is letting me down / alsways redirects me to Quat.LookRotation and Vec3.RotateTowards
@warm adder my first google result https://stackoverflow.com/questions/1171849/finding-quaternion-representing-the-rotation-from-one-vector-to-another
thanks! looking into it now
Also instead of Rotate About Axis - just multiply the quaternion with ur position to rotate
not sure if that is possible. But I kinda like the Rotate About Axis (tree billboard shader, so X/Z always 0), saves maniuplation beforehand
could just 0 out the unwanted axis 🤷♂️
So, to get radians / degrees, I need to construct a quaternion. I'll still need to convert from the quat to radians then, looking up that formula now
or, you know - you could just multiply the position instead of doing that weird conversion to get rotatet around axis working (which is just a worse way of multiplying a quaternion)
🤔
I don't understand, I apologize I'm not very good at coding This only returns the value of forward if the game object rotates nothing happens. I tried using transform.rotation.y but you can see why that has its issues the documentation helped me a bit but i am still having trouble implementing it.
I'm trying it out in code first, to wrap my head around it etc.. https://pastebin.com/qYTvfCrW I'm getting 0,0,0 for the cross product though, the Quat is always empty too. You see what I am doing wrong?
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.
One of the vectors in your cross is a 0-vector likely the rotation.eulerAngles
I suppose what you want to use for the cross product is transform.forward instead of transform.rotation.eulerAngles
Ah yeah. of course. Thanks!
is there a way for me to generate .meta files "outside of unity"? i've been trying to apply URP's FSR patch, but unity doesn't find .meta files and does not generate them because the folder is immutable.
all the new FSR-related files that have been added have show this kind of error, and the files are as if they weren't there, indeed because no meta files were generated.
Asset Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/amd_fsr.hlsl has no meta file, but it's in an immutable folder. The asset will be ignored.
Ok, Getting there. I've got this attached to a plane, trying to make it rotate towards the camera. But I'm getting... Interesting results.. https://pastebin.com/6Mcj8nRg
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.
I'm pretty sure I can use all those functions in shadergraph too. So if I get this to work I can recreate it there
Was curious as to the performance of setting a TMPro.text member on every frame (hard to profile/test this use case, thought I'd look at the code first). The setter is:
/// <summary>
/// Base class which contains common properties and functions shared between the TextMeshPro and TextMeshProUGUI component.
/// </summary>
public abstract class TMP_Text : MaskableGraphic
{
/// <summary>
/// A string containing the text to be displayed.
/// </summary>
public virtual string text
{
get { ... }
set
{
if (m_IsTextBackingStringDirty == false && m_text != null && value != null && m_text.Length == value.Length && m_text == value)
return;
m_IsTextBackingStringDirty = false;
m_text = value;
m_inputSource = TextInputSources.TextString;
m_havePropertiesChanged = true;
SetVerticesDirty();
SetLayoutDirty();
}
}
Am I right in understanding that as long as the text is the same from frame to frame (m_text==value) that none of the expensive redraw happens?
Or do I need to dig deeper into subclasses of TMP_Text
Yes you're right
It’s just yaml, you can edit them in any text editor, by there is no other tool but the unity editor that really understands them perfectly
Sorry for the late respond - was trying to mimic texture alias by combining multiple texture together (customizations), so that I don't have to render more than 15 unique overlay texture at the same time.
How do you make a character move? I use 2020.3.18
how do i do this? the red orb is the player, which shoots a projectile by instantiating a bullet and adding a transform.right force. then, i want it to bounce on that blue orb like the trajectory i drew with my distinct drawing skills
(i want the bullet to "bounce" off the orb in that way)
i've tried using bullet.addrelativeforce, but it doesn't give the effect i want.
It's not clear how you want it to behave
should it always change the velocity 90 degrees to the right?
Vector3.Reflect on collision and use the result as the new trajectory
yeah, depending on where the player shoots
i'm gonna try it out
that doesn't clarify it at all but if reflect works then cool
i just have to understand how reflect works first haha
it sounds like he just wants it to ricocet on collision
which is what reflect should do
@stiff spear @devout hare and how do i get the inDirection? i'm applying a force to move the bullet (from the gun barrel), i don't think RB.velocity would work(?)
when i did it, i wrote my own physics and just moved the transform every frame
i can try to pull up the code
i mean its a bullet right? all you really need is a raycast at the front of the object
no need for rb
well, i use it to apply rb.addforce
but i could also use rb.velocity
by the way, if you want, that would be great
this is what i did
in update loop
on bullet object
you can ignore the component stuff
hit point is just a empty game object at the front of the bullet
so i can position the raycast correctly
stupid question: this is a bullet based shooting mechanic or a ray based?
the initial angle is just your bullet spawn point forward vector
Velocity is the direction the object is moving, by definition
its a moving bullet, not raycast, but i use raycast to detect collisions
its less expensive than a rigidbody
which may not matter in your case
you could use that instead of making raycast based collisions yea
just another question: what is that network destructible component?
its irrelevant, its related to a separate system
okay
i'm gonna try to implement it and see how it goes. Thanks a lot, you saved me lol
np, all you really need is the vector3 reflect on collision and replace the current movement vector with the newly reflected one
and make sure to reflect it against the hit points normal, idk if a normal rigidbody collision will give you that but yea
it works flawlessly, you can look at #archived-works-in-progress
Very epic
Does anyone here use a particular commit or versioning convention for their end-user Unity projects (as opposed to libraries or assets)? I'm trying to clean up my project and my development process, and I figure adopting a commit convention would help.
you should tag whatever is released to users with the real app store version / steam build number
no, redraw will happen in UGUI if the layout changes
mytmp.text = "hi"; //redraw
mytmp.text = "hi"; //redraw?
no
won't redraw
i couldn't find the code for the UGUI child class, but assumed "no" based on the check in the parent
it's probably OK - i'm only thinking ~100 text objects for ~1 second, so .. even if the redraw-ed, it probably wouldn't be worth testing/profiling
if nothing else changes* it will not cause the component to recalculate the text rendering
but lots things cause transforms in UGUI to change which trigger a redraw
(they don't otherwise change for that 1 second)
Okay, but what about versioning and commits before then? (Assume that I will be sharing builds with partners before launch, e.g. beta testers or publishers or localization)
I tend to use a modified gitflow strategy - I simply check into master and commit with "WIP" as I go, and then squash those commits (and remove all the "WIP" messages) when an actual stable milestone is reached, and tag that release (so I can go back to it easily).
I was doing full gitflow for a little while (ie, branching off of "develop", naming the branch after a feature, then merging it back) but it was more hassle/paperwork than I needed, and also I tend to "mostly" stay on target for a feature, but there's a lot of cleanup and ancillary work as I go, and I didn't like mentally "asking my manager if I could do that work"
non-professional feedback is rarely actionable on an engineering level
treat testflight and google play beta releases as releases
they get tagged
there's an audience for ad-hoc distributed game builds, and it's a bad one*
beta testers, publishers, localization people - you will give them a non-latest build, they receive a polished / limited build, so it goes
you give them "master," and you've just made them nonprofessional QA testers
lol
idk personally im leaning towards a steam beta test when at that stage, but yeah releasing the latest build doesn't make sense at all
cuz you can do override keys (ie personally hand out beta steam keys on the discord) and as long as your under a few thousand keys its all good
but itll be a hassle to keep track of
the automation process was a hassle but it worked fo rme
i wish you could release a steam build without touching the website
so it goes
lmao fair
i haven't delved much into steam works yet
i watched the vid on uploading a build
but thats it
steamguard-cli is an important ingredient in the automation toolkit
one interpretation of the lack of automation in steam, the app store, google play is that successful apps rarely need daily binary update support
your client should be thinner, essentially
hmm i see
the best games on apple app store nowadays are apple arcade, and those get released once, updated twice, then done
why do automation
so fair
we'd have to ask the steamdb guy how often steam game binaries are updated
itd be hype to hit on a valheim-type success but thats like the lottery basically lmao
would be an interesting study question
ye true
i wonder if they have any stats on stuff like that as is
ah i guess not -- quick google turns up nothing on steam work stats
valheim is rarely updated anyhow
much more so in february march of last year than now
but even then, at most 3 builds a week... might as well upload yourself
it's gucc
20-30 million DAUs using the last few days as a point of reference
comparing this game, which was indeed upgraded frequently, to a website
like a website with that number of DAU probably gets updated 3x a day or more
jeez eh
so personally i push back against the frequent update mindset
it is adverse selection
even at the highest scale
yeah fair
if you are doing something in software that needs to be updated 3x a day, which could be really cool, how can you make tha ta website?
i keep frequent backups but thats just cuz my computer was really unstable (black screen issues) until i reseated the graphics card
as opposed to - how can i update a steam game 3x a day
but im talking a backup every three to five days
which isn't too frequent tbh
if i uploaded to steam itd probably be months between builds
unless it was bug fixing after a build
then itd probably be as soon as the bug as solved or w/e and the build was stable
good question lol
hard to say
im gonna have to develop a core group of beta testers
that i refer to and trust
but keep it smallish and try to get a range of hardware to see how the game perfoms
id say tho for the most part your beta testers might just be chance at a poor review in an early state
esp if its really public ie steam play test
but idk
its hard to say without having been thru it
How would one make a pathfinding AI that can navigate an arbitrary 2D collider shape, and is performant up to, let's say, 50 instances of it running at the same time. I don't need AI in my game yet, but I'd like to be ready for the future, and if possible, try to program the other parts of the game to be ready for that if necessary.
you could just use an out of the box solution like the a* pathfinding project, theres a free version for 2d
if you wanna code it yourself i recommend this tutorial for isometric maps https://www.youtube.com/watch?v=u3hfWOCiIPg
What's the license for that if I want to publish my game at some point?
im not sure but it says on the page lemme get the link
That said, my 2D space is not a grid, there's triangular and circular shapes as well.
hmm that might be a little tougher, im not sure what the solution would be tbh
If you make the grid small enough, it will look good enough
I suppose what I could do is somehow hardcode specified paths that the AI will follow.
It would only be a last resort though, as that's an ugly solution, and for the bigger space ships I'm planning it sounds like a pain to do all of them.
writing your own pathfinding code isn't too tricky if you want it to be grid based lol but yeah idk otherwise how you'd do it
(Basically, I want AI crewmembers to automatically go to damaged components of the ship during combat like the reactor and repair them.)
i see
How about writing the pathfinding for impostors that can sabotage your components?
i dont think it'd be too hard either
the pathfinding code you can reuse
writing the ai code is a little trickier
i used that tutorial i linked above for pathfinding
and then the ai which controls the behaviour
i used this tutorial https://www.youtube.com/watch?v=ejKrvhusU1I&t=1s
First video of my Utility AI tutorial series. Here, I give a general overview of the popular video game AI frameworks, where Utility AI fits in amongst them, and then dive into the specific logic behind Utility AI. Actual Unity coding will follow in the next videos! Just starting out with YouTube so sorry for my sub-par video recording/editing s...
its v thorough and indepth
its one method thats easy to implement, flexible, and it is contrasted vs behaviour trees and finite state machines
tho later on the tutorial implements a finite state machine to act as controller, basically to transtition between three states -- move, execute and decide
I haven't hooked up the utility AI to the pathfinding yet
but this is what it looks like (blue line is a drawn gizmo, green and red dots are drawn primitives that incidentally murder the frame rate lol)
took me maybe 10 days total to code ngl
but im kind of a newb
I have a bash script that should auto push my Unity Cloud iOS builds to appstoreconnect. I use the same bash script on every project, but for some reason on this project I'm getting errors. Can someone take a look at this error and see if you can figure out what I'm doing wrong?
👍
these are the best kind of problems to have because they mean the sky isn't falling 😄
I was looking in wrong project. indeed the scripts are where they should be. I wonder if my git is ignoring them
some of the default gitignores do ignore sh iirc
spooky
might have something to do with my org ID or my app name because of line 3 of the bash i'm using
echo "Uploading IPA to Appstore Connect..."
#Path is "/BUILD_PATH/<ORG_ID>.<PROJECT_ID>.<BUILD_TARGET_ID>/.build/last/<BUILD_TARGET_ID>/build.ipa"
path="${UNITY_PLAYER_PATH}"
if xcrun altool --upload-app --type ios -f $path -u $ITUNES_USERNAME -p $ITUNES_PASSWORD ; then
echo "Upload IPA to Appstore Connect finished with success"
else
echo "Upload IPA to Appstore Connect failed"
fi```
not sure if it gets org_ID and Project_ID from unity dashboard, or if it gets it from my project settings
what does echoing those get you?
it auto uploads the build to appstoreconnect.apple.com for me. super convienient way to do ios builds without a mac
another weird thing though, is the build shoudl have failed if this script failed, but for some reason, its not telling cloud build that it failed. oh well. at least i was able to look at the console. i have to run to get groceries, then maybe i'll figure this out
gl
oh that build path is my github directory
one of my environment variables keeps getting deleted (this time its my itunes password). I've added it back. hopefully this solves it.
I was hoping someone could help me figuring out how to create a player movement script that allows the player to move through the WASD keys, through clicking to move, and through click and dragging. Basically I want to fit all these three movement features in a 3D project without them cancelling each other out. Thanks in advance
That is 'easy' to do, at least if you are using the new input system. You basically only move when you get one of those events. Each movement type doesn't really need to know about the others for the most part except to cancel each other out (WASD canceling the clicking to move movement)
What I can’t quite seem to do is to cancel one method out when the other is in use. How would you go about stopping them from interfering with each other?
that's something you need to decide
what happens if you start using WASD when in the middle of a click to move?
which has priority
That almost completely depends on your implementation. But most likely something like this.
if (_shouldCancelMouseMove )
{
_shouldCancelMouseMove = false;
return;
}
Or you could have like an int which is the current movement methods priority which is set when input happens, that way only the one with the highest priority happens.
Question: How do you add a handler to an eventInfo whose delegate takes an internal type parameter (specifically an enum)?
Hi I've been using Playfab for most player account data up to this point. I know Playfab has an inventory system available but from what I've read, it seems like you can't edit the stats of your inventory items with it. I want to create a system where once the player buys a weapon from the shop, they can purchase upgrades for it to increase its stats. What is the best way to accomplish this with safe data that stays bound to the account (not just the device and could be lost if uninstalled, so playerprefs i think would be a bad idea). Maybe im misunderstanding playfab's capabilities? Or is there a better way. Thanks
Maybe this is totally something Playfab handles but what you're describing makes it sound like you need a custom API that handles your end user accounts and the associated data.
Can the profiler do a call stack, or break a function down into its smaller parts? I know my update function is taking 150 ms but I dont know which part of it
Use Unity.Profiling.ProfilerMarker
you can also turn on deep profiling
Okay, did that, thank you
Wit hthat ive figured out the problem but not how to fix it
I'm calling Twexture2D.GetPixel whatever 257^2 is like 5 times in a single frame.
Is there a more efficient way to do this:
//Tex is a Texture2D
float[,] heights = new float[257, 257];
using (s_ProcessHeights.Auto())
{
//convert data
for (int x = 0; x < 257; x++)
{
for (int y = 0; y < 257; y++)
{
//tex.GetPixel(y, x).r;
s_GetPixel.Begin();
heights[x, y] = tex.GetPixel(257 - y, 257 - x).r; //this is just me fiddling until i got it to work right
s_GetPixel.End();
}
}
}
I can move the 257-x and the coordinates swapping to the script that generates the images so no math needs to be done
Is there a way I could like, dump the contents of the PNG to a 2D array like this?
I could also have it be a 2D array of Color32s and just use the r value later but that seems like a waste of ram
Or... could I make a compute shader to do this? This seems like a good multithreaded process
or use C# jobs
Depends on what you're doing with each pixel? ComputeShader is prob the champ here though
create an inventory item that corresponds to the upgrade to apply to the weapon
calculate the stats by summing the base and upgrade items' effects
are you sure this is the case?
wouldn't an event with greater visibility than its types be a compile error?
it is in java
use Fastlane to automate app store uploads
I'm writing the r value to a heightmap array to put onto a terrain gameobject
I just found out playfab can handle playerdata seperately with a json file so im going to try implementing that with a list of all the upgrades the player has purchased for each gun that will be retrieved when they enter the armory and updated if they purchase anything
Oooh I’m excited, I’ve never written a compute shader before. Also they are all 257x images so bandwidth shouldn’t be an issue.
I'm using a URP shader graph in my game that creates an ammunition bar that shows the bullets left in the mag and one dissapears each shot. Works well. I'm trying to use the same exact shader graph in my armory scene however, and the image shows up fine in both scene and game view but not once i play it. So it must be an issue with rendering. Worth noting that the ammo bar was in world space and this is on the UI layer so that could be part of the problem.
Open to other options that would be easier than updating the fill amount of this shader graph for each weapon stat. Im sure i could just have each bar representing a stat level be its own game object that can change sprite/color individually but i feel like having 40 game objects for something like this is bad practice.
hey, does anyone have the formula to calculate the timestrecht when changing the pitch of an audioSource?
I thought it was Pow(pitch,2) but am not sure :/
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class NetworkManager : MonoBehaviourPunCallbacks
{
// Start is called before the first frame update
void Start()
{
Connect();
}
public void Connect()
{
PhotonNetwork.ConnectUsingSettings();
}
public void Play()
{
PhotonNetwork.JoinRandomRoom();
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
Debug.Log("Tried to join a room and failed");
PhotonNetwork.CreateRoom(null, new RoomOptions { MaxPlayers = 4 });
}
public override void OnJoinedRoom()
{
Debug.Log("Joined a room - yay!");
}
// Update is called once per frame
void Update()
{
}
}
JoinRandomRoom failed. Client is on NameServer (must be Master Server for matchmaking) but not ready for operations getting this error
Are you using any UVs position to do so ?
And yeah 40 gameobjects are maybe too much, there should be another way to do so like repeating the square image according to the number passed to the shader
Hi are someone know how to make a top down world generator?
I am getting an internal event via reflection that has an internal type as a param.
Are there any people using Unitask?
I can't find out how to check if the task is running. I want to make some kind of spawner with an interval timer. I want to prevent the method from being executed again. Ended up using bool flag variable but this does not satisfy me
I used Unitask in one of my previous project. Did you try the IsCompleted flag? it's in awaiter for sure, you can get that from UniTask as GetAwaiter
@noble stream Yea I tried but im beginner with this framework and async aswell (trying out before diving into theory hole).
I want something like this
private void Start()
{
StartSpawn();
StartSpawn(); //should be ignored or give exception
}
private async void StartSpawn()
{
if (started) return; // or write exception
await SpawnInterval(.5f);
}
private async UniTask<bool> SpawnInterval(float seconds)
{
while (!IsFull())
{
await UniTask.Delay(TimeSpan.FromSeconds(seconds));
Spawn();
started = false // or something like that
}
return true ; //or started = true;
}
Feels like that Im thinking wrong about how i can work with that
I am having a problem with Rpc's and Generics. I am getting a compile time error with my code:
public class NetworkHandler<T> : NetworkBehaviour where T : unmanaged
{
private NetworkVariable<T> _networkVariable = new NetworkVariable<T>();
public void InitGeneric(T value)
{
Debug.Log("Testing Generic Method");
}
public void SetValue(T value)
{
if(!IsOwner) return;
if (NetworkManager.Singleton.IsServer)
{
_networkVariable.Value = value;
}
else
{
SubmitPositionRequestServerRpc(value);
}
}
[ServerRpc]
void SubmitPositionRequestServerRpc(T value)
{
//TODO implement Rpc logic
}
}
and the implementation would be like this:
public class NetworkTest : NetworkHandler<int>
{
private Random _random;
private void Start()
{
_random = new Random();
Debug.Log("Testing Less Generic Method");
InitGeneric(10);
}
private void Update()
{
//Post a random value and sync over network
if (Input.GetKeyDown(KeyCode.Space))
{
SetValue(_random.Next(1, 20));
}
}
}
This is the error (Too long for discord to handle so its a screen shot). I am using the Netcode for gameobjects package
Because with my implementation the generic would be hard typed on compile time (because of the interface inheritance) I dont get why it is giving errors, Any thoughts?
Assets\Script\CarController.cs(42,71): error CS1011: Empty character literal
Have you checked that line to see if there is an empty character literal?
Chars cant be empty you can set them to "\0" if you want them empty
i dont even now what that is
That would be an empty char literal
thx
char a = '\0' would work
doesnt work
UniTask Completion issue
You'll need to provide code
how do i do that
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
//wheel colliders
public WheelCollider wheelFL;
public WheelCollider wheelFR;
public WheelCollider wheelBL;
public WheelCollider wheelBR;
//torque colliders
public float engineTorque;
public float brakeTorque;
//steering angle
public float maxSteeringAngle;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetAxis(''Vertical'') > 0)
{
wheelFL.motorTorque = engineTorque * Input.GetAxis(''Vertical'');
wheelFR.motorTorque = engineTorque * Input.GetAxis(''Vertical'');
wheelBL.motorTorque = engineTorque * Input.GetAxis(''Vertical'');
wheelBR.motorTorque = engineTorque * Input.GetAxis(''Vertical'');
}
if(Input.GetAxis(''Vertical'') < 0)
{
wheelFL.motorTorque = brakeTorque * Input.GetAxis(''Vertical'');
heelFR.motorTorque = brakeTorque * Input.GetAxis(''Vertical'');
wheelBL.motorTorque = brakeTorque * Input.GetAxis(''Vertical'');
wheelBR.motorTorque = brakeTorque * Input.GetAxis(''Vertical'');
}
}
}
char a = '\0';
vid on yt i tried to make a driving car
You didn't follow it very well then
And that char a at the end was an example to you, not something for you to copy
what are you doing with char a. It seems to not be used at the moment
idk
if(Input.GetAxis(''Vertical'') > 0)
//shoud be
if(Input.GetAxis("Vertical") > 0)
yes
I can't believe we're in #archived-code-advanced
Yup, i was already scared when he didnt know how to post code
@deep blaze there is a chat thread for code-beginner these question should probably asked there
oke
Okay so. If I wanted to set a heightmap from script it would have to say be 257x257 right? And does setheights start from 0,0 or 1,1? Logic says 0,0 but I have a 257x 2D array and it still is off by 1 somewhere giving me this weird gutter
You can have a "heightmap" of whatever resolution you want. It's your heighmap. But I'd normally expect 256x256
And wdym by "SetHeights"? Are you talking about Terrain or something?
Oh I thought it had to be a power of 2 + 1
TerrainData.SetHeights()
oh - maybe start with that context 😵💫
and no, it's zero based, of course
it's an array
You're right about power of two plus 1
so yes 257x257 makes sense
do not use generics
you do not need a networkvariable or networkbehaviour
declare the typed variable where you need it
unity's "codeweaving" (IL bytecode instrumentation) is throwing the exception you see
i cannot tell what value your generic code is providing but it is not worth banging your head agsint for little value
It was a design choice, I wanted the network logic and the other seperate from each other and on different layers of my code structure
I posted it on the github page of netcode for gameobjects as an issue and will move on for now. because you are right that it is just a little detail and not a big problem
that's the spirit
it's baffling unity still has a codeweaving based approach to this
instrumenting IL code, unlike java bytecode, is a huge pain in the ass
i see
if it's an enum, try redeclaring it in your own code
and see what happens
You get errors because the types are not compatible 😛
runtime errors right?
Yeah
you can use the information in the exception to construct the right type
which will be a subclass of Enum or whatever
then use the general int to enum methods to construct an instance of that type or whatever
but i don't know why that would matter since aren't enums erased in c#? no idea
I tried using Enum, but it returns null :/
okay so help me understand
you can retrieve this internal event correctly
but not a type in one of its delegates parameters? why?
also what assembly is it?
like what's the goal
// In Unity assembly
internal enum HierarchyChangeType { Add, Remove, Move }
internal static Action<VisualElement, HierarchyChangeType> hierarchyChanged;
I want to get the hierarchyChanged event and add a callback to it so I can run some code when the event is raised.
It is the UITK assembly
hmmm
but in react you do not have to do this
so why do you have to do this in UIElements
anywya, if you really need this
the source of UI toolkit is open
you can (1) redeclare these
(2) create an assembly info that marks your assembly as a friend
InternalsVisibleTo
if you didn't want to modify their code at all
create an assembly info with the name DynamicProxyGenAssembly2
and it will be able to access the internal types @urban warren
does that make sense?
you will never have the dynamicproxygenassembly2 in your project, which is why i chose it
so you'd have a directory with asmdef DynamicProxyGenAssembly2
and it references com.unity.ui
Because I am working on a split view and was wanting to be able to register callbacks with the panes when they are added/removed.
While I could do what you suggest, it feels overkill. I am like 90% sure there is a way to do it with just reflection.
no
reflection in C# is not powerful
both of these methods are superior to reflection anyway
because they both use the real approaches - one is making the source what you want, and the other is to respect the internal declaration
sort of 🙂
you can use the DynamicProxyGenAssembly2 to only provide the bridge you need to this internal type
you should already have "callbacks" when components are mounted
i do not know what the terms are in unity land
but UIElements is architecturally React
at least aspires to be
There isn't :/
would you know how to achieve this in react code?
modern react?
UIElements should have an equivalent of useLayoutEffect
you are not the first nor last person on earth who needs to know the size of a layout in order to do something
Nope, never used react
so i really feel like if you are fishing for the internal methods you are doing something wrong
you should try my asmdef approach just so you ycan see for yourself
I do not need to know the size. I need to know when a element is added as a child
that those events are a world of hurt
i don't think you do
you can do that easily by checking every frame if there is a new child, and move on
What do you mean?
try to create an asmdef called DynamicProxyGenAssembly2
and add a reference to com.unity.ui in it
Not if you remove one child and add another one right after the other.
you can solve that programming problem i believe
list difference is a known quantity
i don't know if you need this approach though
writing UI is tricky
How? It is a closed loop? The best I can think of is to keep a list of 'previous' children, but that seems needlessly expensive and complicated
'previous' children, but that seems needlessly expensive and complicated
you should look at the UIElements source to understand that there is an incredible number of "lists"
an incredible number of lists this frame compared to lists the previous frame
and it has no meaningful impact on performance, because computers are purpose built to compare lists
based on how hierarchyChanged's source code
Well compared to simply using the internal event that does exactly what I want 😛
it seems like it is only used by UIElements editor code
it doesn't do what you want
where did you get the idea that it does?
its name?
No, because it is called from the hierarchy's .add method
have you looked at the source?
Yup, that is how I found it.
well
we can talk about how to make a split pane view
or we can talk about something that doesn't make sense
it's internal for a reason
it doesn't do what you want
lol what?
i'm not sure why you need to know when you add elements using this event in particular*
it sounds like you are chasing a theory about efficiency
it's not how this stuff works
in order to avoid having to compare a list of 1 element to another list of 1 element... you are doing a big to do
can you maybe talk about how you are using this event?
why is a list of previous children expensive?
since when?
like what is the idea
i can see why you want to know when the children have changed
but you do not need this event to do that
and it will not provide a meaningful efficiency gain
I need to add a GeometryChangedEvent callback to all the children of a specific VisualElement. So I need to know when one is added or removed so I can register or unregister the event.
because you are trying to calculate the size of something?
help me undestand the big picture here
because you could just have a dictionary of the children you've called this thing on
and move on
it will not have a meaningful impact on performance
i don't see much behavior in the ui elements code that depends on this event
which makes me really skeptical you need to use it
My main problem with using the list/dictionary approach is that when it will be called is not specific. Which may not be the end of the world but I feel like it makes things messy imo.
When a child is added/removed I need to also add/remove a divider for it (used for resizing a child)
Along with that I need to register a GeoChangedEvent
okay
Right now I am opting for just having a AddPane(..) and RemovePane(..) methods that you use instead of the normal Add(..) and Remove(..)
https://github.com/tomkp/react-split-pane/blob/v2.0.3/src/SplitPane.js this is a high quality split pane
component
in react
which does not use componentDidMount
so you could translate it directly to UIElements provided you knew what this stuff did
are you sure AttachToPanelEvent isn't what you need?
for your constructor?
your pane should look like
<SplitPane>
<Pane> ... </Pane>
<Pane> ... </Pane>
</SplitPane>
@urban warren https://github.com/tomkp/react-split-pane/blob/5fa31020fac4e06989fda776547c389109a6d19b/src/SplitPane.js#L349 this is the core of the logic
react only reruns render when state changes
it appears to rerun when the children change, which is fine
that is just comparing two lists
obviously in the browser it is running in real time without a meaningful performance impact
so in my opinion you are overthinking this
anyway writing UI code is a long journey
@urban warren are these the behaviors you want? http://react-split-pane-v2.surge.sh/
this guy did a really good job
UIElements IS "Unity React"
so if you can understand his stuff you can get a super high quality split pane
what is your goal?
to spawn enemies until you have reach a maximum spawned, then once those enemies die, resume spawning?
async UniTaskVoid SpawnerStateMachine() {
var enemies = new List<Enemy>();
var maxEnemies = 4;
var spawnPeriodSeconds = 0.3f;
// for as long as you want...
while (true) {
// if the number of enemies is too few
if (enemies.Count < maxEnemies) {
// wait a beat
await UniTask.Delay(TimeSpan.FromSeconds(spawnPeriodSeconds));
// spawn one
enemies.Add(Instantiate(enemyPrefab));
} else {
// wait until an enemy dies / is destroyed
await UniTask.WhenAny(enemies.Select(enemy => enemy.GetAsyncDestroyTrigger().OnDestroyAsync());
}
}
}
that's it
you can pass cancellation down if you need
i don't want to make it too arcane
because ti should be clear how you can pause this
Check thread that i created
why
what i wrote here is much clearer
well what's your goal?
is it to spawn enemies until a certain number are on the battlefield
and then as they die, resume spawning them?
yes
okay
do you see how the code i wrote expresses almost verbatim that logic?
you don't need this actual spawn preserve forget stuff...
you don't need the awaiter
or actual spawn versus spawn
the point of unitask is that you can express things like a game loop / a state machine / a behavior
does my example make sense @spare pond ?
Ok let me implement WhenAny and i will share result
well my code makes certain assumptions
about how your game works
so if you don't know what's going on here
you're not going to have something that works
if your enemies are not Destroyed
then that trigger will never fire
you could also monitor the list of enemies until it changes some property
Im using objectpool so my objects not getting destroyed
I cannot use whenany because its takes array of elements when i cannot give that array coz im not allowing to
it's up to you if you want to use the bad logic in there
in that thread
it doesn't make sense
i'm not sure what you mean by you cannot give that array
surely you have a way of knowing which enemies are spawned
there are a lot of ways to achieve that
you can adapt the example i wrote for an object pool
the key thing i'm illustrating is how to write game logic using unitask
you just write it
you try to express in written words what your logic should do
and the magic is that you can turn that english language into code
you seem like you are concerned about "garbage" in the thread
Because the classes that store this array do not provide a function to display this array
if* you want to await an event you can use a UniTaskCompletionSource but that obscures what is going on
I can expose this to a method Gameobject[] GetObjects() but will it allocate memory?
do you want the right answer?
this memory allocation will not matter
why use unitask if you are concerned about memory allocations
you're using event which allocates arrays
private void OnEnable()
{
_stash.OnRemove += (c) => StartSpawn();
StartSpawn();
}
private void OnDisable()
{
_stash.OnRemove -= (c) => StartSpawn();
}
^delegates allocate and there is absolutely nothing you can do about it
but you just didn't know that
and yet... nothing happened to your computer program?
I mean, UniTask exists to provide an alternative to Task that allocates less 😄
why use Unity if you are concerned about memory allocations*
it's just to say that if this is your concern
this maze is not meant for you
anyway, i wrote you an elegant example you should think about
you can look at UniTaskCompletionSource to see how you can "signal" a task
which is a superpower
because I'm making a game for mobile and user will touch this spawner alot
var destroyed = new UniTaskCompletionSource();
destroyed.TrySetResult(...);
// elsewhere
await destroyed;
yeah... it's not going to matter
you are already allocating somewhere
people go on this journey... the issues with allocations are due to flawed logic
which is why i am suggesting a more elegant approach to describing your game logic
using unitask
that's why people use it
the elegance of it all
that avoids the mistakes where allocations matter
but you're already doing _stash.OnRemove += (c) => StartSpawn(); which allocates
it's unavoidable. you simply cannot use public event ... without allocating
indeed, you will be allocating everywhere all the time in Unity
allocations in and of themselves do not matter
but when they do matter, it's because it's a huge allocation, happening every frame, with some dumb logic
not because you are using event or WhenAny
how often?
anyway this is my perspective and it depends on your goals
if your reaction to discovering you are allocating is
to somehow explain away this allocation
that's a good part of the journey but one which you can do on your own
because surely, if you think that _stash.OnRemove is okay because it happens very rarely
so does GetObjects()
i am glad you are considering this perspective though @spare pond because it will make you a much, much better programmer
think of it as an expanding brain meme:
- all allocations are bad
- some allocations are okay
- when allocations are bad, a different mistake was made
- allocations do not matter, because i don't make those mistakes
@final steeple c'mon that's a pretty good one
lmao
@undone coral In WhenAny part how can i instead of checking for destroy trigger
check for trigger that is called when removing an object from the collection
Maybe if I was more familiar with JS and also React I could translate it to C#. But even so, it looks like the architecture is quite a bit different than UITK (though definitely has similarities), so I'm not really sure how much could really be carried over.
And if it does things the way I think it might, it wouldn't follow the same design pattern that UITK uses for its elements.
I was wanting to get the hierarchy change event so that I could then create a UITK event for it, then I could something like RegisterCallback<HierarchyChangedEvent>(..) and it would be nice and clean and could be used else where.
I appreciate the suggestions though! 🙂
How to debug development build in VS?
Is it possible to use the System.dll for .NET 4.5 with Unity?
Why would you want to do that?
look at UniTaskCompletionSource
this will let you await in one place and TrySetResult (i.e. signal, or finishing awaiting and return a value) in another place
ok, thanks
render is whenever stuff in props changes, run this
anyway it's close
Right, I was kind of figuring that. As best as I can surmise, the controls for changing the split are added to the panes in the render method(?). Which is the important bit that I am trying to do 😛
Its fine though, using my own AddPane() method will work fine enough
Quick question
Can I execute a static method using the -executeMethod from a custom package folder ?
What do you mean "custom package folder"?
So I have a custom package in my project eg Package/MyCustomPackage
I would like to execute a static method with exeMethod flag from that package instead of assets folder
" exeMethod flag"?
Command line argument -executeMethod
Oooh, yeah should work fine
Do you have a ln example, I seem to be able to it fine from a script in assets but it can find that script in my package
No sorry. I just know how Unity handles that stuff internally mostly so given that info, it should just work.
But really at the end of the day it is just a guess on my part
yes
I have a Unity class with many events that I need to subscribe in Awake() and OnDestroy(). I'd like to stop forgetting to write the += and -= in those methods.
Anyone have a nifty/clean way to do something like:
private void Awake()
{
SubscribeEvents(true);
// NetworkManager.OnServerSendStartBattle += HandleServerStartBattle;
}
private void OnDestroy()
{
SubscribeEvents(false);
// NetworkManager.OnServerSendStartBattle -= HandleServerStartBattle;
}
private void SubscribeEvents(bool isSubscribing)
{
// ??
}
Obviously I could just if/else the entire thing but.. I was wondering if there were something you geniuses could come up with that's cleaner. 🙂
this question has been asked before but I couldn't find a reasonable solution in the googles: https://forum.unity.com/threads/better-more-elegant-way-of-unsubscribing-from-event-action.640180/
Sorry this isnt quite code but... Im trying to install a custom package (Visual Pinball Editor) through the package manager in Unity as detailed here: https://docs.visualpinball.org/creators-guide/setup/installing-vpe.html
Everything seems to go okay except it's not adding the Visual Pinball Menu item like the document says it should. Any ideas? (Unity 21.2.12, Have tried restarting already).
This doesn't answer your question, but is there a reason you subscribe/unsubscribe in Awake and OnDestroy instead of OnEnable and OnDisable?
Well, it will behave slightly differently. If you do it in Awake/OnDestroy, your scripts will still react to events when they are disabled
Which is confusing
But maybe desired in some cases
you added the scope in the project settings and added it via the package manager?
are there any errors / warnings in the console?
That's fair - not a concern here since the scripts aren't disabled ever, but I'll move it there since it's more correct
There isn't a good solution here because you can't pass event members to methods. You'd have to be using something other than regular C# events to be able to make something like that.
void Start() {
this.OnServerSendStartBattleAsObservable()
.Subscribe(HandleServerStartBattle)
.AddTo(this);
}
see unirx's implementation of AddTo
Does that RemoveFrom() implicitly later?
my issue is that I wanted to get away from adding a line that +=s and one that -=s because it's getting gnarly:
yes
cool, i'll check that out.. i keep hearing about unirx and just avoiding it
to a variety of things, include a gameobject, component, etc.
yeah... you wanted to do
BattleManager.instance.gameEvents
.OfType<BattleDefeat>()
.Subscribe(bd => ...)
.AddTo(this);
and model your events hierarchically
interface IHasTarget {
GameEntity target {get;}
}
interface IHasSource {
GameEntity source {get;}
}
abstract class BaseEvent {
string description {get;}
}
abstract class GridEvent : BaseEvent, IHasTarget, IHasSource { ... }
class MoveGridItemEvent : GridEvent {}
class StealGridItem : GridEvent
// one kind of ui
gameEvents.OfType<GridEvent>()
.Subscribe(ge => RenderAnimatedGridArrow(from: ge.source, to:ge.target)
.AddTo(this);
// another kind
gameEvents.OfType<BaseEvent>()
.Window(5)
.Subscribe(events => SetHistoryTray(events))
.AddTo(this)
void SetHistoryTray(IList<BaseEvent> events) {
Enumerable.Range(0, events.Length).ForEach(i =>
view[i].text.text = events[i].description) ...
}
``` @misty glade
Yeah, I added it in the project settings as the documented instructed. I do see where other Visual Pinball items have been added to the existing menus of the unity editor, like there is now a Visual Pinball menu in the Component menu.
I do have errors in the console but they seem to be talking about game objects and materials, which I think would be fixed if I could do the next step of importing a table that's been built in VP, which I have some of already.
The Visual Pinball menu item is suppose to have an option in it to import those .vpx files.
if unity throws an error when compiling some code it will not finish compiling and you will not get the menus
void SetHistoryTray(IList<BaseEvent> events) {
Enumerable.Range(0, events.Length).ForEach(i =>
view[i].text.text = events[i].description) ...
}
what's this bit do @undone coral ?
just saying like
oh you have a history tray
ahhhhh, i get it
generically show the description of ht eevents in it
since the .descriptions on the base event
yeah
OK - this is a little wacky for me but looks really cool
so all this stuff you want to do with the events
it can be more general
here's something really mindblowing
this might be the solution to my biggest problem right now - animations
While you type, let me tell you my problem and you'll see why my current implementation sucks. I have this chonker Battle state object that is maintained in the battle manager. When the server tells me something's happened (actually, a lot of somethings - like 10+ "actions"), I update the Battle object and emit all these events in order so the UI can animate them. The UI literally just catches all the events and adds them to a coroutine spooler to unspool them and play them. The problem is the UI can't tell what the data is DURING the animations because the Battle object in the manager is "in the future" after all the animations have played.
So if there's two "gets hit for 10 HP" actions, after the first one is played, the UI doesn't know what to display (-10? or -20 hp) because that state isn't saved anywhere.
Sooooooo my current solution was to piggyback before/after variables in ALL of the events, which is a massive pain in the dick.
My proposed fix was to create a copy of the Battle state (nontrivial) and have one be the "true" state and another be the "animated/delayed" state. But that sucks too.
// get all the scripts on your game manager
// that handle events
var eventHandlers = GetComponents<EventHandler>()
.Where(handler => handler.enabled)
.ToArray();
// create a thing where when you subscribe to this,
// the events are going to be animated with the
// "right" delays due to animations or whatever
var animatedEvents = new Subject<BaseEvent>();
// get all the game events which may come instantly
// from the server
BattleManager.instance.gameEvents
.Select(event => Observable
// process them one by one inside coroutines
// think of this like a "route handler" in a web
// app which may have multiple handlers that should
// process something sequentially and asynchronously
.FromCoroutine<BaseEvent>((observer, cancellation) =>
ProcessGameEvent(event, eventHandlers, observer)))
// part two of the magic that makes it all sequential but
// asynchronous
.Concat()
// part three: pump the messages into "animatedEvents"
// AFTER the animations have occurred
.Multicast(animatedEvents)
.Connect();
private IEnumerator ProcessGameEvent(
BaseEvent event,
EventHandler[] handlers,
IObserver<BaseEvent> observer) {
// this is the API for event handlers
// for example, showing a toast should come from
// this context object, or making the screen shake
// or showing a menu
var context = new EventContext(event, ...);
foreach (var eventHandler in eventHandlers) {
// i.e., a coroutine
IEnumeator processor = eventHandler.Handle(context);
// workaround for https://forum.unity.com/threads/yielding-a-nested-ienumerator-waits-a-frame-even-on-break.772352/
while (processor.MoveNext()) {
yield return processor.Current;
}
}
// you have handled this event
observer.OnNext(event);
observer.OnCompleted();
}
``` @misty glade
@misty glade more sophisticated example = https://gist.github.com/doctorpangloss/cc6c646ac00d2cc66e21af14cd8484e7
i can hear your mind exploding
Give it a moment to explode, I'm still digesting the code hah
do me a favor doctor p
start doing that lol
lol
the snippet has a lot of science in it
you can look at the sophisitcated examples of "event handlers"
those are straight from spellsource and use different names for things
but it's the same idea
it's like a "copy these into here" method
except at the moment Connect is called, the game events now come in AFTER their corresponding animations have completed
then you can subscribe to "animatedEvents" and know that when you get an event via animated events, it will be right when all teh animations are complete
including, e.g., the game data at that moment of time
which is almost always what you want
connect is Subscribe for subjects (which are like mailboxes)
hm.. interesting.. so like, hang on, you're saying that my "state" doesn't advance until the event is done being chewed on by the subscriber..?
I'm not really getting that
OK.. I'm going to really dig into this and try to understand it
this is basically a way to do "execute a bunch of async handlers sequentially, or sometimes in parallel, whatever makes sense)
"and give me the opportunity to show the right state at the right time"
the problem is i'm trying to do something sort of advanced and .. don't really have my head around UniRX as a beginner, so that's not going to work out well
"or, if i want the latest state, i wanna see that too"
well
this is how i do, in spellsource
in a super non spaghetti code way
"let the attack animations play out, but let you do all the actions you can as quickly as possible"
kind of like in hearthstone, but even better
you can just do all your attacks without waiting for them to animate out
Right.. that's what I definitely WANT to do because making a "lagged copy" of the entire stateful object just fort he UI to operate on is shit, because everything the UI points to is the "real" copy of the state - i'll have to literally be switching it back and forth depending on whether i'm animating
yeah in this example you get the lagged copy
hearthstone is the exact model i'm thinking of
if you want it
well... there you go
good luck with this
you got the science now
this is how you do it without spaghetti code
it's actually very much how our game works - there's 5-10 actions, each of which animate automatically (like dudes on the battlefield attacking the opponent) but the HP of the interim state needs to be correct
OK thanks - i need to scoop up my brain a bit and stuff it back in my cranium
lol
https://pastebin.com/mm8EpC8E I've been trying to figure this out for hours now... I get an error on the very last line, the one that says "}" (Line 43 in pastebin). I get this error:
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.
the error position is weird, but you're probably erroring on line 40
if _controller.walkableTiles is empty it will error
it'd help if you shared the whole script not a snippet
oh sorry - yeah Mad is right
I misread your error
ArgumentOutOfRangeException is known to be misreported on the closing bracket of the method
It is. I am doing something wrong elsewhere then
Hi just got your message, what do you mean by "UVs position to do so"
I'm using a URP shader graph in my game that creates an ammunition bar that shows the bullets left in the mag and one dissapears each shot. Works well. I'm trying to use the same exact shader graph in my armory scene however, and the image shows up fine in both scene and game view but not once i play it. So it must be an issue with rendering. Worth noting that the ammo bar was in world space and this is on the UI layer so that could be part of the problem.
Open to other options that would be easier than updating the fill amount of this shader graph for each weapon stat. Im sure i could just have each bar representing a stat level be its own game object that can change sprite/color individually but i feel like having 40 game objects for something like this is bad practice.
alright what do you think
Quick question about how System.Guid works. If I create a new guid, and convert it to a string or byte array, but never recreate the guid after domain reload. Does that mean it can be regenerated again (or more accurately increase the chance of it being generated again)?
GUID is just a 128 bit randomly generated number
I'm not sure how you converting it to a string or byte array is relevant
I guess because I wasn't sure if there was some sort of internal 'table' of previous generated GUIDs to decrease the chance of duplicate GUIDs
there is not
GUID collisions are possible but incredibly improbable
Alrighty, do you happen to know how GUIDs are generated?
Using a pseudorandom number generator
as all random numbers are generated
it is merely a 128 bit number
I see. Well thanks!
Got another unrelated and less concrete question.
What sort of memory impact do loaded ScriptableObject assets have vs just using normal C# classes?
there's a native C++ part to them. They need to be manually Destroy()ed
so - slightly more impact
plus that extra memory management concern
Right, but I guess I am wondering what the memory overhead is compared to a normal C# class. Like 1000 C# classes vs 1000 SOs
Yeah
The SO is basically a normal C# class, plus some fields for the fact that it inherits SO, Plus the native bit
whatever is there on the native side
I am converting a GUID to a string to a PropertyName, as doing lookups with PropertyName is several times faster then with GUID, but man does it feel dirty haha
Learn what’s new and upcoming for the scripting backend in Unity, including changes planned for the goals of maximizing performance, providing better debugging capabilities, and delivering long-term stability.
Speakers:
Josh Peterson (Senior Manager, Software Engineering, Unity)
Join the conversation on the Unity Forum: https://on.unity.com/3L...
now that is a terrifying video title
It's about them migrating to CoreCLR, .NET 6, etc
oh ok good stuff
Sounds cool
Also confirmed NuGet support finally
Also replacing asmdefs with the modern SDK-style csproj
(asmdefs still work, but they'll be converted behind the scenes)
Is it just me, or is the audio messed up?
Yeah it's doubled lol
it's messed up
Yeah, I'm hoping that'll actually be the point when we can start recommending async without caveats 😄
The cancellation token stuff actually shipped in the recent 2022.2 alpha
If it has a cancellation token that automatically cancels based on playmode changes, and maybe object destroy stuff it'll be pretty nice
Though I have some concerns with how it was implemented at the moment
What shipped? AwaitableCoroutine?
Nah, every MonoBehaviour has a CancellationToken property you can use now
Oh weird
and the Application class has a global cancellation token representing when the game exits
Which is really nice
but having one on every MonoBehaviour is going to result in a bit of memory overhead with how they've implemented it
(a lazily allocated CancellationTokenSource on every MonoBehaviour)
AwaitableCoroutine sounds more like the right way to do it based on what was briefly mentioned in the talk. Might be worth asking for them to elaborate in the .NET thread
coroutines are common, but are still the "minority" in the realm of MonoBehaviour instances, so you'll end up with a ton of memory wasted on null pointer storage
Agreed
like an enemy might have 6 components, only one of those will perform coroutines
So those 5 other components don't need to store a token
I imagine it'll add up fast in a big project, since that's 8 bytes of memory for every single MB instance
4 bytes on 32-bit
Either way I think an external storage location would be a better idea
Seems worth it for potential ease of use
Some kind of mapping from instance ID to cancellation token
Then it can still be exposed as a property on the MB, but doesn't waste memory when you don't use it
I'm just excited about not having my own implementation to handle exiting playmode
I imagine they already plan to make that optimization, the feature JUST shipped in an alpha after all
but I wanted to bring it up anyway
Yeah, Application.CancellationToken is really nice
Now I just want a proper accessor for the main thread's sync context 
I'm not familiar with that. Is it a nicer version of having to mess with the PlayerLoop? https://github.com/Cysharp/UniTask/blob/18f2746f0d30a1b870d9835f2f16d15b56476a33/src/UniTask/Assets/Plugins/UniTask/Runtime/UniTask.Threading.cs#L89
A synchronization context is how you queue work on another thread
I have a helper class here for using it: https://github.com/NewBloodInteractive/com.newblood.core/blob/master/Runtime/MainThread.cs
So you can just do MainThread.Post(method, null); and it'll get called on the main thread
The main reason to have a proper accessor is that some other code could get called before the SubsystemRegistration callback and change the sync context, and then it won't get the one for the main thread
An extremely unlikely occurrence but it'd be nice for it to be an impossible one
For reference, the sync context is also how task continuations are called
So when you await Something(), the rest of the method after the await is queued on the sync context, which is how it'll stay on the main thread normally
and to answer this, yes
I got another API design question. I have a custom collection type that will have methods that function the same as the ones in ISet such as IsSuperSet(..) and Overlaps(..), along with ones that function similarly and will have the Exact word in them (ie. IsSuperSetExact(..), OverlapsExact(..)).
So here is the question, do I do my naming scheme and do ContainsAll(..), and ContainsAny(..) along with ContainsAllExact(..), and ContainsAnyExact(..) which to me is a bit more intuitive. Or do I use the naming in ISet for consistency?
Arguably it's better to follow existing conventions so that the knowledge is transferrable between different types, but if your type implements the ISet interface you can technically do both
Just implement the ISet methods explicitly so they're private to consumers using the concrete type, but usable by casting to the interface
Yeah, that is what I was planning on doing if I did my own naming.
That said, I'm a bit biased -- I have the meanings of the method names for most of these etched into my brain with a laser
So I don't really feel confused by them, but others may disagree
What's the Exact bit do 🤔
Yeah, I don't really use the ISet interface (or implementing classes) much so I kind of gotta think about what some of the methods do sometimes
Would be nice if Unity shipped the proper XML doc files so you could just hover over the methods to get an explanation like in any other C# project 😔
Which methods don't have the comments show?
It is a collection of nodes of a tree, and by default Contains will check for the node but also if any of the nodes in the collection have the specified node as a ancestor. So the Exact variants of the methods will only check if the collection has the specified node and not check ancestors
Unity doesn't ship the framework doc file, so you just don't get any of it
Maybe I'm just used to Rider where it finds it all automatically, or maybe I'm looking at different stuff
What? I get doc commends for all Unity stuff... but not C# stuff :/
Another thing where Rider's just putting in work I suppose
Rider likely includes the XML file itself, yeah
As a workaround though, you can add the netstandard.xml file yourself and it works
I don't have that either
This file goes in uh
sec
Editor/Data/NetStandard/ref/2.1.0/
and then you'll get the proper doc stuff in VS
Uhh, where is this?
Your Unity install dir
C:\Program Files\Unity\Hub\Editor\version probably
But once you've put it there, it works as expected:
It's just unfortunate that it's not included in-box (maybe by mistake)
OOOH, thank you @final steeple!
Here I was thinking I had installed C# stuff wrong this whole time
It annoys the hell out of me when I forget to copy it in there lol
Yeah, I wondering why Unity doesn't include the xml for the base C# doc commends...
Man I love Rider lol
(Littered with keywords so I can find this again when I forget ^ )
Well I have it too and don't have doc comments!
(Well now I do thanks to Zombie)
Must be a setting somewhere then surely. Or maybe it's fairly new? Are you on the EAP rn?
Your Rider installation might be using a normal .NET SDK installation rather than Unity's
Which would explain why you had XML docs without needing to manually add the file
If you search for External Symbols in the settings what do you have there?
Everything's ticked for me
Same
Hrm. Maybe Zombie's right and I just have it installed in such a way where Rider's finding it. Or there's another setting somewhere. Good there's a workaround at least 🙂
Can anyone please help here?
Has anyone implemented Oauth with strapi as backend?
Hi guys does anyone know if we can use the auto geometry 2d feature via code?
Hi Guys, I want to build a Match3 Mechanic for mobile. The question now is, should i build it a Canvas or with normal transforms. The Pros for Canvas would be:
- Scaling the board, that it always matches the screen would be a lot easier
- Grid Layout is also there out of the box, which would also save me some work.
For the Cons i cant say that much, but i have a feeling that there are some pitfalls doing it in a canvas, that I am not thinking of right now,
What are your guys opinion on this? How would you build something like this?
cons are performance, with large enough grid the layout will eat up quite a lot of perf on any updates to the scene graph
So which size would a large enough grid have?
are we speaking of 10x 10
or 1000 x 1000
just to have an idea on when is starts to matter
its best to use ui for the whole thing, just be aware that things that require layouting are expensive, and in general changing any recttransform property can be expensive
And when i want to use particles on the merge field
would this become an issue?
Performance wise
@plucky laurel
particles are not natively supported in ui
youd have to use a plugin, from asset store or github
but no particles dont participate in rect updates
okay
its just a mesh
multiple canvases, for base ui, separate one for the "grid" , the grid i would write myself
What do you mean by writing the grid yourself? No using the grid layout?
yes, not using it
since the grid layout handles all cases it can, you can write a very small and specific code that does what you want with minimal performance impact
Can you [BurstCompile] normal methods, assuming they only use blittable types? Or is it exclusively Jobs only?
Hey I was thinking about updating from 2019.4.15f to 2019.4.37f, but apparently there are some major differences in the canvas scaling area... .WorldToScreenPoint methods are working differently and my whole UI is glitched...
Previously I did
Vector3 pos = camera.WorldToScreenPoint(p);
pos /= canvas.transform.localScale.x;
to convert from world space into canvas camera overlay space.... But now its not working. Any can suggest a fix? Thanks
Important note is that my camera viewport rect has 0.956 height, the top bar is cropped out of camera rendering.
I've tried various calculation fixes for this, but I'm struggling with one thing: After changing camera viewport rect the size of the camera overlay canvas does not update until I move the camera a bit.... :/
Hi. How to swap two scripts on two different gameObjects?
Destroy(GetComponent<YourScript1>());
AddComponent<YourScript2>();
It's a bad idea to remove scripts though, maybe you mean swapping the values of a script?
Yes
create a temporary go
values are needed
it'd be great if this was possible
AddComponent<YourScript2>(scriptObj);
or as java's every object has .clone();
Thanks
it's probably easier if you just write your own clone function
Yes maybe
another quick question
why Can I see private properties?
and set it.
just updated visual studio
public void CopyData(YourScript original)
{
someInt = original.someInt;
}
because nextPlayer is static I assume
It is not. just declared
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class CameraAdjust : MonoBehaviour
{
#region Get Components
public GameObject player;
public GameObject cinemachineObject;
CinemachineFramingTransposer composer;
#endregion
public Vector2 offsetEnter, offsetExit;
public bool exitEnabled;
// Start is called before the first frame update
void Start()
{
#region Set Components
CinemachineVirtualCamera vcam = cinemachineObject.GetComponent<CinemachineVirtualCamera>();
composer = vcam.AddCinemachineComponent<CinemachineFramingTransposer>();
#endregion
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
//if player enters
if (other == player.GetComponent<Collider2D>())
{
//adjust camera
composer.m_ScreenY = 0.5f + offsetEnter.y;
composer.m_ScreenX = 0.5f + offsetEnter.x;
}
}
void OnTriggerExit2D(Collider2D other)
{
//if player enters
if (other == player.GetComponent<Collider2D>() && exitEnabled)
{
//adjust camera
composer.m_ScreenY = 0.5f + offsetExit.y;
composer.m_ScreenX = 0.5f + offsetExit.x;
}
}
}
Hello, I have this code on one object which works
the only important part is that OnTriggerEnter2D and OnTriggerExit2D works
when I copy the object this is attached to, only one object works
is player set for both objects and is exitEnabled = true for both objects?
add a Debug.Log("TriggerEnter) into your enter method to see if it gets called for both objects
will do, one moment
it triggers for both, but seems the camera code only works on the blue square on the right
Since Start() is called twice with two objects it's probably overwriting something
So, the Debug.Log activates for both objects but not the rest of the code.
May be an issue with Cinemachine and trying to have 2 objects reference the same camera object
I will look into that thank you.
I had thought it would not overlap if the code is on two separate objects
it seems it had something to do with that, thank you
i need help setting up a body system similar to gorilla tag, with the head and arms. i already have the movement mechanics done. i just want to give the players a design so it’s not just hands
hey I need help with a jump. when i turn my player while jumping I spin around the initial jump point.
Probably not an advanced question... #💻┃code-beginner #archived-code-general
and use #854851968446365696 on how to ask questions correctly
thanks nobody answered in general
could anyone help me ?
depends , what is your issue?
I have been making this helicopter game it works great in the editor but once I build it some of the controls don't work
So I'm trying to figure out how to make a grinding system in my game. The issue is I don't even know where to start, I just need a way to attach the player to this gameobject once they enter the trigger collider
I was trying to send a gif of what i meant but I guess i cant -_-
are there any errors in the log of the build game?
gif`s get removed you can post a video
K, I'm trying to make it the same as the game Jet Set Radio
so you want to restrict player movment along the grinding path
Yes
So i need some help im pretty stuck. As you can see in the picture, I'm trying to implement a weapon stats upgrade system to pay for stat increases on each gun. I'm using playfab to store player data and this data (the amount of upgrades purchased in each stat) obviously needs to be updated to player data in playfab too. Problem is I have about 15-20 guns to store these 4 level variables per gun. I was looking for a way to store this data in player data of playfab accounts and be able to update a single variable when something is purchased. Then i need to grab the specific levels of the gun selected which would be better if i didnt have to make an api call every time a weapon is clicked on so maybe have some kind of dictionary or something i can read from? I hope im making sense of this
I've been trying to get this script working that parents the player to the rail from this trigger. But it doesn't work at all
don't use prefabs to store data. use scriptable objects
not sure what you mean. Im not using prefabs to store player data
oh playfab my bad. its late lol
ironically scriptable objects are still the answer though
have SO's function like containers for data pulled down from API calls and you can handle them with simple dependency injection. don't make an API call every click, just let the local version get away from the playfab state until you have a good opportunity to make an explicit save
like when you exit the menu
public abstract class PlayfabDataObject : ScriptableObject
{
public abstract void Save();
public abstract void Load();
}
[CreateAssetMenu(menuName = "Playfab Data / M4A1")]
public class M4A1PlayfabData : PlayfabDataObject
{
public int DamageLevel {get; set;}
public int DamageProgress {get; set;}
public int FireRateLevel {get; set;}
public int FirerateProgress {get; set;}
public int MagSizeLevel {get; set;}
public int MagSizeProgress {get; set;}
public int ReloadLevel {get; set;}
public int ReloadProgress {get; set;}
public override void Save()
{
//TODO: update the playfab data
}
public override void Load()
{
//TODO: override data with playfab data
}
}
something like that
I think i've got something along those lines working, thanks
i do a similar thing with local saves. each scriptable object knows its own type and instance name and saves/loads itself according to that, completely idiot proof
Hi folks 👋 . Does anybody here have experience working with Unity Physics in some detail? I am looking for some assistance on a golf ball simulation - specifically the behavior of the ball on ice.
Best to just ask your question and folks will respond rather than look for a single individual. Also, Unity's physics could probably be discussed in #⚛️┃physics but if it's relative to code overall, one of the coding channels would be fine.
hey how make resize camera in 2d project use c#
and resize in script and move smooth
Hey all, I am stuck with this issue, does anyone have any ideas?
https://stackoverflow.com/questions/71767609/unity-c-dll-crash-when-calling-handler-passed-from-unity-to-c-sharp-wrapper-to
I have found a C++ lib https://github.com/yhirose/cpp-httplib and I am trying to write a C# wrapper around it to be able to use it from Unity.
To bind handlers for POST / GET routes you use;
server...
Will a public function that grabs a hidden static function get the correct subclass version?
E.G
public static string SaveDataType => "TRACKED";
public string GetSaveDataType => SaveDataType;
and then in a derived class
public new static string SaveDataType => "COUNTER";
If I call
SubclassObject.GetSaveDataType()
Will it return base class static ("TRACKED") or the correct one "COUNTER"
but this is a situation in which the derived class is a variable of BaseClass
e.g
Baseclass x = new DerivedClass();
x.GetSaveDataType()
How can i create a code 128 Barcode in unity from string?
maybe you can get this working in unity
https://github.com/SourceCodeBackup/GenCode128
Tested, it will return the derived class static string's value given that the derived class overrides the GetSaveDataType property.
Otherwise it will return the base class static string value.
Thanks 👍 I imagine there would need to be some new "virtual static" type signifier to have it work without a function override.
Appreciate
how can I install this?
download the last releas and copy the "GenCode128-2.0\src\GenCode128" folder in your unity project
in the root folder or assets folder?
i put it in the root folder of the project. How can I use that now? Do I have to write using something at the top?
You should have put that in a folder in your Assets/ for Unity to detect and compile it.
The namespace to include can be determined by checking the source code
Ah, you shouldn't be including all the library, just the source code
Weird that the outputted DLLs weren't ignored from the start by the user that pushed to the repository
alright what do i need?
As Malzbier said, everything in the GenCode128-2.0\src\GenCode128\ folder
but that is this
i just copied it
(you can get rid of the .csproj)
You should have 4 files under a folder in your Assets/
idk where you found these bin and obj folders though
yeah i downloaded this but i need not the master
master is the branch the download originated from, it's not relevant
Yep, because that code isn't made for Unity, it uses things in the System.Drawing namespace, that are not available in Unity
So you need to convert the bit of code that generates the image barcode to something compatible with Unity
It shouldn't be hard, from what I can see they just use Image and FillRectangle to draw the bars.
You would use a Texture2D for it to be compatible with Unity
I have never tried to create and modified textures at runtime, so no idea
Google time!
yess
why i cannot update the load screen while im loading my game syncronously?
i try to upload the screen at some parts of the code doing...
loadingUIRef.UpdateLoadingScreen(description, currentPercentage); ```
but they dont update the loading UI
I know its not a great solution but can't you generate black and white rectangles
i maybe already have a solution @umbral basin but thanks
Good luck
can someone tell me why my UI does not update while my loading script is running?
Not without seeing your code, no.
I DONE IT GUYS I LOVE YOU ALL
how long have you guys been using unity for?
UI gets blocked because of the continuous expensive sync calls, solved by changing the method to a coroutine and do yield return null whenever i want to update.
yes
hard agree
no i mean like u guys r advanced
so how many years have u been using unity
😏
just curious
I have general C# intermediate question that I can't seem to find an answer for anywhere else. So I'm hoping someone here may have an idea: I am still struggling trying to use ENCAPSULATION properly. So in my base class (Animal) I setup the encapsulated property here:
private TMP_Text speechBubbleTMP;
public TMP_Text SpeechBubbleTMP
{
get
{
return speechBubbleTMP;
}
set
{
speechBubbleTMP = value;
}
}
and then in my child class (Bear) I try to set the text and get issues when it tries to run :
{
Animal animal = new Animal();
animal.SpeechBubbleTMP.SetText("Test encap"); // ENCAPSULATION
// SpeechBubbleTMP ^^ is a property I am Setting to specific text
}
I get this in the console when I try to run that "encapText () " method.:
UnityEngine.MonoBehaviour:.ctor () " ```
And I realize why that's happening- but HOW can I Set this encapsulated Text property FROM the child class properly ????
The issue does not come from the encapsulation itself, it comes from the new Animal();, which is not allowed because Animal is apparently a MonoBehaviour.
Use AddComponent<Animal>() to add the script to the current object, or Instantiate to create a copy of a prefab which has the script on.
Otherwise your property is right, and it (the property access and method call) would work as expected.
@fresh salmon yes someone else suggested the same thing- but that will not work for this because I don't need to add the base class as a component to the child or instantiate it when the child should just inherit from the parent class right?
Then don't make the class inherit from MonoBehaviour if you don't plan on attaching it to a GameObject
public void encapText ()
{
SpeechBubbleTMP.SetText("Test encap"); // ENCAPSULATION
// SpeechBubbleTMP ^^ is a property I am Setting to specific text
}```
this is all you need
if Bear : Animal then YOU are an animal inside the Bear class
OHHHHHHHHHHHH
Oh yeah I missed that, methods declared in base class can be called from child ones
Also since your property does nothing else than getting or setting a field, you can convert it to an auto-property:
public TMP_Text SpeechBubbleTMP { get; set; }
The compiler generates a field for you at compile-time, you don't see it, it works the same as your current code
hmmmm ok- Im still getting a Null Reference when the encapText runs
NullReferenceException: Object reference not set to an instance of an object
Bear.encapText () (at Assets/Scripts/Bear.cs:22)
Bear.MakeSoundAndUI () (at Assets/Scripts/Bear.cs:17)
Animal.OnMouseDown () (at Assets/Scripts/Animal.cs:79)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
well did you ever assign a value to that field?
Have you passed a TMP Text in it
you need to tell it which TMP_Text you want to set the text for
For example:
[SerializeField]
private TMP_Text speechBubbleTMP;``` add SerializeField here and you can drag and drop it in
THATS IT!!!! thanks you so much @sly grove and @fresh salmon !!
I was screwing myself up because I didn't know you could publicly expose it with [SerialzeField]
anyone have recommendations for something that could generate some kind of dependency diagram out of vs code? tried googling but nothing seems to be coming up for C# at least
like i just want an overview of what is touching what to help me refactor and restructure
from an existing codebase
I don't know about tools to generate dependency diagrams, but what immediately comes to mind is just good old fashioned namespaces. Start organizing your scripts into folders and subfolders on a per-namespace/sub-namespace basis. Then you'll be able to see at a glance at the top of your scripts which scripts are dependent on what by means of the using statements. If you're really strict about namespaces, this can be super helpful for seeing dependency patterns.
A workaround if you can't find anything is you can start splitting your code in to Assembly Definitions in Unity. That way you'll get compile errors unless you reference your assembly definitions correctly. Plus they don't allow circular dependency, which should help you clean up stuff and keep it modular
yeah that's the plan but i thought it'd help to get an overview of what i have to actually figure out where to draw the borders
Hey guys i installed sqlite for unity and put the files in but if i want to run the app on android it says "there is no sqlite3" how can i fix that?
where I can change the name of the folder that is hosted in the appdata/LocalLow= _filePath = Application.persistentDataPath + Path.DirectorySeparatorChar + "UnityDebug.txt";
?
the folder name is based on your project/company name in project settings
i was able to get a bad version of what I wanted working with splines
ty
this looks hella cool :O
Hey does anyone have a good way to make a texture atlas with varying sized textures? Let's just say that I need it to be like that please thank you!