#archived-code-advanced
1 messages · Page 75 of 1
It's there, but you should also be able to just Ctrl + Click it.
ah yeah I see that, couldnt F12 into it or anything
also only shows up for me during runtime on a breakpoint
Does anyone know how I could make an efficient but simple inventory system that supports trading between players and mining resources.
I really just want to go with the easiest inventory system possible
Meaning no pickups, no sorting, nothing like that
If I obtain an item, it will be put at the bottom of my inventory list
Removing an item from one list to add to another is pretty trivial, this is probably more #archived-networking related
Well couldn’t it just be played data
I’m using coherence multiplayer right now and it works really well
I just need to be able to transfer player data
Yes that is networking related, depends what data you are trying to send. The actual trading mechanic is easy, just add/remove from a list
Im unsure what you mean "player data", that is pretty vague
For anyone looking for a solution to this in the future: I got IPreBuildSetup working (I had my test assemblies set up wrong before so the callbacks weren't being called). And there has to be at least one NUnit test in the class or the interface callbacks won't be run. And make sure you don't rely on any static data in the set up method, it occurs before the assembly reload so any static data will be lost. I ended up setting a value in PlayerPrefs so I can read it in RuntimeInitializeOnLoad. Not elegant but it works. I'll take it, since there's no built-in way Unity provides for differentiating between Play Mode triggered by tests vs. Play Mode triggered in other ways.
When are you supposed to use EditorCoroutines vs regular coroutines? I've found some code I have to work with that's full of the former, even though I'm sure the code is meant to run at runtime.
Anyone know the best way to have a stable frame rate for 500 instances of a zombie prefab? I am using 2021.3 so can't use ecs.
I should mention too it's for WebGL
Look into gpu instancing
Goign to need to pull lots of tricks to pull that off on webgl
Also look into billboarding
Already tried that but does not do anything.
Have you tried profiling to see your actual bottleneck?
I believe it's because I have just 500 clones of a prefab in my hierarchy. I have heard of pooling the instantiate in memory however I can't for the life of me find anyone discussing how to do this besides lists and ECS but I wouldn't know how lists would interact with the process of instantiating a zombie prefab and have it live in the scene besides having it add to a list and whoever is in the list gets instantiated into the scene but would be the same as having clones of the prefab in the hierarchy ?
Simply having 500 objects in the hierarchy means nothing
Use the profiler and see what is taking up performance
Noticed the GPU isn't being utilized and its just tanking the cpu. So working on that now.
I really doubt that you would be able to run 500 instances of complex object in WebGL. You gonna need to make a lot of sacrifice like only using a defined height, not using pathfinding, using billboard, no physics component, etc.
That is the question and the journey. Will update if I ever get it working
Does anyone have a good resource to share, or can give me some insight on the following?
What should I keep in mind while managing cameras in Unity for performance. Is it fine to have a script that'll cycle through them and just disable the gameObject if a camera is not needed?
Do you neccesarily need all 500 zombies at once, on screen? Or can you just pool and reuse them
Complete side mention, but if you do that, keep the colliders as simple as you can (like box colliders). The physics checks when you enable / disable meshes can impact it more than the drawing of the meshes themselves. Fun things you learn benchmarking 🙂
Or better yet if you can get away with no collisions, it will greatly speed up the enable/disable of your pooling
Hey everyone! I have a quick question on an inventory system. Once I make an inventory system I want to create a warehouse system, where I can store items in that warehouse but it’s private only to my items. Since it’s a multiplayer game, each player can access the warehouse but instead of seeing other people’s items, they see their own private warehouse where they can stash and take items.
SOunds like it would just be another inventory
an inventory of inventorys keyed by player id
Yes
Is anyone familiar with coherence?
It’s a multiplayer networking service
That makes multiplayer very simple and easy
And they have accounts for games
So I’m guessing I can attach the inventory to that player data
Hey guys,
I'm getting back to use Unity after a few years. Just checking on of my projects and trying to modify some stuff.
I don't know how widely Zenject/Extenject is used nowadays but I have a question about it.
I have a gameObject which is called Player, It has GameObjectContext and MonoInstaller and I bind an integer there. I have a prefab (Character) which is instantiated by Player and Factory. In Character facade class, I use method injection and trying to get that integer. But it is failed and it is not resolved. How can I fix that issue ?
You have to use the zenject instantiate method, by injecting a factory into the thing that does the instantiation
There's examples on the zenject docs
I need some help understanding a bug I'm having. I have a compute buffer containing indices that are important. Those indices are then transformed into position and set on another compute buffer with a compute shader. So
Indices = {1,4,5,8,10}
for loop with indexI of length of indices (5)
{
get the first indice
transform it into a position
verify if position is valid
if so
{
finalpositions[indexI] = position
finalIndices.append(indexI)
}
}
the final positions buffer and the final indices bufer are pre seted on a material, all of this has been going on through a command buffer so that each step is sequential
then i copy count the finalIndices length
and I call commandbuffer drawmeshinstanced with the material
the material then does
for loop with indexI of length of final indices
{
float3 position = finalPositions[finalIndices[indexI]]
draw the object in that position
}
after this loop is done, the loop is repeated with a diferent set of Indices, while reusing the previous command buffers (final indices with a count value set to 0, and finalPositions untouched)
After all the commands are set, the command is executed at a certain point of the event.
The problem is, the meshes flicker. Is like some data is leacking from loop to loop, or at each loop, data is being calculated slightly diferent (the position seems to be the same, however, slightly diferent since a random generator is returning diferent values)
Im not sure how to debug it, the frame debugger changes the results when checking the diferent steps meaning that it is not returning the same values at each call, even if the calls and the data is always the same
I think there might be somethign about command buffers that I don't understand
I'm using factory as I said.
In this way:
using UnityEngine;
using Zenject;
namespace Infrastructure.Factory
{
// TODO: More option for instantiating like Unity
public class ZenjectResourceFactory : IResourceFactory
{
private readonly DiContainer _container;
public ZenjectResourceFactory(DiContainer container)
{
_container = container;
}
public Object Instantiate(Object @object)
{
Object instance = Object.Instantiate(@object);
_container.Inject(instance);
return instance;
}
public Transform Instantiate(Transform transform)
{
Transform obj = _container.InstantiatePrefab(transform).transform;
return obj;
}
public Transform Instantiate(Transform transform, Transform parent)
{
Transform obj = _container.InstantiatePrefab(transform, parent).transform;
return obj;
}
public Transform Instantiate(Transform transform, Vector3 position)
{
Transform obj = _container.InstantiatePrefab(transform).transform;
obj.transform.position = position;
return obj;
}
public Transform Instantiate(Transform transform, Vector3 position, Transform parent)
{
Transform obj = _container.InstantiatePrefab(transform, parent).transform;
obj.transform.position = position;
return obj;
}
public Transform Instantiate(Transform transform, Vector3 position, Quaternion rotation, Transform parent)
{
Transform obj = _container.InstantiatePrefab(transform, parent).transform;
obj.transform.position = position;
obj.transform.rotation = rotation;
return obj;
}
}
}
Bump
Found the method, I believe you want this
https://github.com/modesttree/Zenject#dicontainerinstantiate
Specifically the prefab one u think
Oh hmm it's just an extension method to turn 2 lines of what you have into 1 line... hrmm
I have a problem with addressable assets when building the project. It is completely OK in the editor.
There is a collection list with 90 elements. They are SOs. It is OK in the editor as I mentioned but in runtime, it logs 360!!! and then I get an exception exist same key because they are populated into a dictionary
Yup, that's true. I should dig further tomorrow. Though it might be a bad practice what I'm doing now. I mean I'm passing player id to the character which is a child, not sure if it is okay, child knows about the parent. But if anyone find any solution for my issue, I'll appreciate that.
Is there any way to get inbetween data of a compute shaders from a command buffer?
For what purpose?
I need the data to generate colliders later on
But it's a conditional case, not all command steps require the generation of colliders
How frequently? Just once?
Yeah, i only want the data once, when needed, to generate the colliders, the command buffer is running every frame, but in some of those frames, I want to fetch the data in between commands to later generate the colliders
I wanted to avoid dispatching another compute shader just for the data
How would the compute shader fetch the data?
if I did a separate compute shader, I would do just get data
Maybe I can add a graphic fence?
Why can't you get the data without a compute shader? Do you need to convert the data into some other format before getting it?
The data is generated in the compute shader
And stored into a buffer?
Not stored between frames
Stored between commands to execute draw calls
But then the buffer get rewritten with new data, more draw calls, and then the frame ends
Im doing this
Is the condition for whether you need to fetch the data known to the CPU when you're making the commands? Or does it depend on the result of the compute shader?
It is known to the cpu when Im making the commands, it doesn't depend at all with the compute shader
Ideally an AsyncGPUReadbackRequest could work, but that only retrieves the data of the final command dispatch, maybe there's a way of doing it with a graphics fence, but not sure
Graphics fence is only used with async compute, which you're not using unless you're executing the command buffers through Graphics.ExecuteCommandBufferAsync
That's my understanding as well, so I think you will have to copy the data to a temporary buffer and make the request on that. You can perform the copy and the request in the command buffer, and provide a callback to read the data.
The problem then is that I need to store that data in N compute buffers, which would kill my memory budget
So the amount of data you need to read back from the GPU + the buffers you're using already for the compute shaders and instanced draw calls is over budget?
Since im using only one buffer only always, then im in budget. However, if I need to create a compute buffer for each readback it can get out of hand and kill the budget
like
for loop of 20 cases, only storing it to one, a bit of memory, but if I then store those 20 cases, the memory of one * 20 is too much
Even if there was some way around needing to store more buffers in VRAM, you would still need the one * 20 memory in CPU RAM if you want to read all the data in a single frame. You can't read the data one at a time in a single frame.
In cpu ram it is not a bid deal, im quickly disposing it anyways
I get the data, check the pool of colliders, apply whatever position it needs to to the pool and dispose of the data
So there's no way to stop a command buffer, fetch the data, and continue?
It would stall the frame, to synchronize the GPU and the CPU.
The GPU is busy processing the last frame while you're creating the commands for the next frame.
Yeah, a bit of delay is expected, I want to at least be able to see how much stalling would it do
You would have to synchronize it 20 times in your example
So that's at least 20 frames of delay.
You might as well just spread the work out over multiple frames.
Process one case per frame.
Until you're done.
No, because i need the draw calls to be done at the end of frame
I think Unity needs to cycle through frames to begin processing async gpu requests. If the main thread is stalled waiting, Unity never gets a chance to process it.
The callbacks have to be called on the main thread, but they can't be called there if the main thread is stalled.
I think I will separate the colliders from the command buffer, and just execute a compute shader for it
Thank you
whats up
so i am making a climbing system and im facing a pretty complicated problem
making a climbing system for a straight wall is a pretty easy task as you just add 2 forces that are the negative normal of the wall and the negative gravity
depending on if the player is pressing d or q i then move him left or right
but what about complex meshes
like rock thats made of angles and straight planes
You prevent the player from going there. You can also increase the amount of animation the player is able to make. (Do not forget IK)
Also, I wouldnt use force for a climbing system. I would make the rigidbody kinematic and simply translate the player along the rock.
The hard part is definitely having animation that fit or limiting the possible climbing position.
Hey guys! So I'm attempting to send bytes from oculus quest 2 but I keep on getting this error: error: ......\modules\highgui\src\window.cpp:281: error: (-215) size.width>0 && size.height>0 in function cv::imshow. I've tried changing the buffer side from python side but to no avail. Any suggestions on how to fix this?
Now it works when I'm using the editor but after having it built and ran on Quest 2, the video stream suddenyl doesnt work
It's an island of zombies and not a event that triggers them. Just a island with zombies everywhere u turn.
everywhere you turn
see? there you go, you don't see them all at once, you have to turn
if a zombie isn't visible, disable it, put it somewhere else, where it comes into view
also I'm pretty sure you can use ECS, just not the newest version
Sounds good I will try using that when I get back in the project.
especially for something like this
I was thinking of maybe having all of them set active to false and than turned back on if it's in range of the main camera render. If that is what ur referring to than yeah I am thinking of that as well. I have to keep optimising until it works. There are so any different ways to do this but very limited things to do for WebGL. I also had thought of possibly just storing it all on a server using normal optimisation and it stream the game to a webgl client.
hello I am trying to make the enemy rotate until the weapon be aiming at the player but I have no idea how to make it can someone help me making it ?
does anyone know of an elegant way to deal with effects such as Stun, in a multiplayer game, when one has client prediction? which can cause a desync in positions
I'm not into networking/multiplayer, but wouldn't you, in theory, make the Server send the Data of "Player X stunned" to all Clients that care about it together with the ServerTime, and then set the Stun Progress for "Player X" on the Clients by getting the DeltaTime between when the Server sent the Data and when the Client received it?
I am trying to figure out what a good spatial partitioning structure would be to use for 'find nearest object to point' type of queries. BVH, Octree, KDTree, BSP, something else? A lot of the objects are static, but some are dynamic. Any recommendations or resources?
I am having a hard time finding actually info on what sort of situations the different trees work best for.
Is the point always the same or it's dynamic?
The query point? Dynamic, lots of queries from different 'random' points
Octree handles updates better than KD tree. But if you can rebuild the KD tree from scratch fast enough, that might not matter. That's about all I know, I haven't used the other structures much.
It might be beneficial to store the static objects in a separate tree optimized for that, and store the dynamic objects in a different tree better suited for updates or quick rebuilding.
For octrees, I can recommend this package for a Burstable implementation:
https://github.com/bartofzo/NativeTrees
Burst compatible Octree and Quadtree for Unity. Contribute to bartofzo/NativeTrees development by creating an account on GitHub.
Unfortunately I don't know what is static and what isn't. I think I looked at that repo, but not supporting removing or updating killed it for me. I guess you could just rebuild though. Thanks either way.
Though, doesn't really help me figure out which tree to use haha
Yeah, rebuilding the tree is very fast with this, assuming you have the bounds ready.
Building the tree is not thread safe, but you can query it from as many jobs as you want.
Yeah, I would assume as much since it populates a single list
Even if you find a tree that supports in place updates, if enough objects move at once, rebuilding it is probably faster anyway than inserting and removing many individual objects.
Hi, working in a project where we have 3D and VR.
I'd like to reliably interact with UI elements in World Space with rays, but not limit myself to a specific VR/XR Framework.
Upon research i could not really find any solutions for an InputModule or GraphicRaycaster that let me use my own raycast. All the solutions were based on existing XR Frameworks.
I began writing my own logic for raycasting into the UI and then handling different Selectables, but i'd like to use the unity-provided core where possible for simplicity reasons.
Anyone has ever made experiences with this or could maybe guide me into a direction?
Thanks <3
I would recommend using the built in EventSystem but writing your own raycaster
it's easier than you think
and then you can use all of the built in stuff like IPointerEnterHandler etc
And it will also interact perfectly with the UI system etc
All you have to do is make a component that inherits from https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.BaseRaycaster.html
and put it in the scene
I'll check it out once i get home. Thank you already!
I just assumed that something so basic, that probably finds a lot of use, is already optimized and accessible somewhere
That's true. So like... I guess just pick a KDTree, Octree or BVH, and hope it works out? Hahaha
If you can jobify and burst your code, then I doubt there's any C# tree implementation that will beat NativeTree's octree, regardless of whether other tree structures are more optimal than the octree for your use case. Burst and jobs will win by all the other optimizations and threading.
I guess that is fair. I was trying to think what the tree needs to be optimized for, and I realized both build and query are quite important. But query probably more so.
the issue is that when stun resolves, the client still doesn't know and continues to predict movement. so you either need to reconcile (not pretty) or find a way to predict the stun, the latter in which im trying to inquire on
hello I am trying to make the enemy rotate until the weapon be aiming at the player but I have no idea how to make it can someone help me making it ? https://cdn.discordapp.com/attachments/885300730104250418/1139523817434251284/2023-08-11_14-36-40.mp4
With the movement example, I can have an enemy come and stun me while I thought I can still move. 200 ms latency is enough time for a stun to happen and create a discrepancy between the move I "predicted" client side and what happened server side. This is where "reconciliation" (or "correction") comes in play. The client keeps a history of the positions it predicted. Being still server authoritative, the client still receives (outdated by x ms of latency) positions coming from the server. The client will validate whether the positions it predicted in the past fits with the old positions coming from the server. The client can then detect discrepancies and "correct" its position according to the server's authoritative position. This way, clients can stay server authoritative while still be reactive.
I am having an issue with Synty Characters in Unity.
I have a transform under the Right Shoulder where I am attaching at runtime a weapon to it.
But if I attach it with no Animator Assigned to the character the gun goes where it supposed to go.
[First Picture]
But as soon as I attached any Animator do the character even with only a simple Idle animation. The gun attachment and my transform gets all twisted.
[Second picture]
I have no idea why.
PS.: the same system with the Unity Third Person Controller character from the starter pack works.
Hello,
I have a game that uses binary to store world save data. In the binary data is an array that stores the position of objects that have been placed by the player.
When I save the data in-game, it works perfectly, however when I forcefully quit the game (alt + f4) or just by stopping it in the Unity editor, and then reloading the save, the array of positions is empty and I can't figure out why yet it works if I save the data first and go back into the main menu scene.
Save Handler Class
public static class SaveManager
{
public static readonly string FactorySavePath = Application.persistentDataPath + "/saves/{0}.sav";
public static readonly string SavePath = Application.persistentDataPath + "/saves";
public static void SaveGameData()
{
if (GameManager.Instance == null)
return;
if (!Directory.Exists(SavePath))
Directory.CreateDirectory(SavePath);
BinaryFormatter formatter = new BinaryFormatter();
string path = string.Format(FactorySavePath, GameManager.Instance.FactoryName);
FileStream stream = new FileStream(path, FileMode.OpenOrCreate);
GameData data = new GameData(GameManager.Instance);
formatter.Serialize(stream, data);
stream.Close();
Debug.Log("Successfully saved to: " + path);
}
public static GameData LoadGameData(string factoryName)
{
string path = string.Format(FactorySavePath, factoryName);
if (!File.Exists(path))
return new GameData();
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
GameData data = formatter.Deserialize(stream) as GameData;
stream.Close();
return data;
}
}
Data Storage Class
[Serializable]
public class GameData
{
public int Level = 0;
public int Money = 350;
public int XP = 0;
public bool CheatsEnabled = false;
public DeployableData[] deployableData = new DeployableData[0];
public GameData(GameManager gameManager = null)
{
if (gameManager == null)
return;
Level = gameManager.Level;
Money = gameManager.Money;
XP = gameManager.XP;
CheatsEnabled = gameManager.CheatsEnabled;
List<DeployableData> data = new List<DeployableData>();
for (int i = 0; i < GameManager.Instance.deployablesInWorld.Count; i++)
{
var deployable = GameManager.Instance.deployablesInWorld[i];
data.Add(new DeployableData()
{
name = deployable.ID,
position = new float[3]
{
deployable.transform.position.x,
deployable.transform.position.y,
deployable.transform.position.z
},
rotation = new float[3]
{
deployable.transform.eulerAngles.x,
deployable.transform.eulerAngles.y,
deployable.transform.eulerAngles.z
}
});
}
deployableData = data.ToArray();
}
}
[Serializable]
public class DeployableData
{
public string name;
public float[] position;
public float[] rotation;
}
don't use BinaryFormatter it is a security risk
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
ah okay.
AES is encryption, has nothing to do with what they were writing
Well what else can you use except BinaryFormatter
BinaryWriter, but still how does encryption even relate to any of this? AES isnt a file writer. If you don't know something you dont have to give advice on it :p
Any data serialization works too, eg JSON.
Oh yeah
BinaryWriter
XOR encryption also works
Also XML
I think you have a big misunderstanding at what writing to a file means. Encryption is NOT related to this at all. XOR encryption is just symmetric encryption (which is garbage alone), and is not a file writer or a format even.
I know what writing to a file means...
Is it when you write to a file
claps
well you do seem to suggest that AES and XOR are file writers or file formats
this would involve re-writing some stuff, but you can store everything as a dictionary, then serialize into JSON, or even XML, Newtonsoft's JSON library has a direct dictionary serializer and desirializer, as to the saving, you have to do the saving at a suitable time, you can have it done on application quit, or add changes to a queue, and have them commited every x seconds or minutes
if you want non-fallible save states you can do a backup system, where save files don't over write new ones, you just write new files, on load, you would load the latest 5 files and load the most appropriate one, this would solve mid-save corruptions by having fall back
I don't know how unity handles crashing/forceful closure, but you can do something like append the current save data to the crash log/dump, if that's even possible
Does anyone know how can I 'extend' a animation curve in this way
Baisacly i want to extend it by some distance and when overlap happens the largest value needs to be taken
do you want to stretch it vertically?
no, on all sides
i mean x and y
like the expand selection tool in photoshop if you know what i mean
i think you can multiply the evaluation by the factor
not sure tho
that would result in a uniform stretch on both x and y axes
can you elaborate on 'factor'
gimme a second
try this on for size
float stretchFactor = 2;
for (int i = 0; i < curve.length; i++)
{
Keyframe key = curve[i];
key.time *= stretchFactor;
key.value *= stretchFactor;
curve.MoveKey(i, key);
}```
@dusty glacier
hold on
btw you only need to this once, not every frame, unless you're changing said frame
you want it scaled around another point?
let me try another way, one sec
maybe stretch the time and value seperatly
i want to split every point on the curve in two points
left green point should split into blue ones and right one in red ones
It's like having a brush trace over the animation curve, or expand selection in various image editing softwares, so it's not just simply scaling the control points.
I'm not sure there's a trivial solution to it, and it also seems kind of odd that you need it?
that, but i would also like to control how much it should scale backwars and forwards if you understand
Animation curves are meant to be stretched and the units of time and value aren't the same to begin with, so tracing a circle doesn't make sense.
on x axis
maybe i should show you what im trying to do
one sec
i am making obstacle detection for character foot movement left box is the position where the foot was and right box is the position where the foot is now and i calculated the hight the foot needs to be lifted to avoid the colision
its show with the dotted curve
the only problem is that the foot has a length and I need to compensate for that otherwise collision would occur
I hope you can understand what I'm trying to do
So you want a function that takes in:
- an animation curve
- a list of all the obstacles and their bounding boxes
- the character bounding box
And output a new animation curve that guarantees the character won't collide with any of obstacles when moving through it?
it should take in an array of heights
Actualy sorry, it should take in the curve i already made
I mean your obstacles clearly have thickness, you can't just take only the height.
it samples mny points
these are boxcasts
they dont overlap
btw, the foot should never go down betwen the obstacles, as you can see there is a dip betwen the obstacles but the path goes over them
But honestly depends on what you are using the output animation curve for, I wouldn't care that much and just cut corners and output an animation curve that's "good enough"
Player won't notice if front of their foot collides with corner of the wall for one frame anyways.
i want to publish it as a paid asset, so i want to make it as good as i can
at least I would like to achieve this effect
Well good luck, there's no trivial solution to it unless you impose some contraint on what the animaiton curve is like.
You can Google keywords such as "image rendering stroke curve algorithm" and you will hit lots of results.
Thanks
Will do
Seems like the formal term is called "offset algorithm for curves."
that is it
Hi, I'm trying to disable and enable buttons. If I do playButton.interactable = false; it works well, but when I do playButton.interactable = true; it doesnt work.
Here's the full code if needed
https://pastebin.com/CsvHAXWN
I am new to Await/Task things.
How do I make an threaded task 'return to' the main thread to schedule a job and then go back to 'threaded' to wait for the job to be over?
Alternatively, launch a task that will run in main thread and wait for that would also work
impossible, once the thread is "return" to main thread the os will destroy it, but the thread can wait the main thread
Are you using UniTask? If so, there are UniTask.SwitchToThreadPool() and UniTask.SwitchToMainThread().
(Or if you are using Unity 2023 there is Awaitable built in but UniTask has some other functionality you might want)
A few things (and this isn't an advanced question, btw) unrelated to your problem:
- Don't name things
action-Actionis a built in class and is gonna cause you headaches if you confuse it. - Don't name parameters the same as your methods. This is just confusing. Make your method names verbs -
DoActionorExecuteActionorDelegateActionwith a parameter(int actionType). - Learn up on
enums and use an enum for your parameter here, not anint. We don't do that in C#.
Now on to your actual problem (maybe). Code looks fine, but you have some issues:
Instantiatecreates a copy of the object in the first parameter.Destroy()on line 43 doesn't do anything if you've linked a prefab, and if you've linked a real object in your scene then it destroys that. You probably meant to do this:
[SerializeField] private GameObject QuitWindowPrefab;
private GameObject _quitWindow;
...
_quitWindow = Instantiate(QuitWindowPrefab, ...);
...
Destroy(_quitWindow);
Now, if I'm guessing correctly, you didn't do it this way, you linked the Play, Settings and Quit Game Button in the actual quit window and you're not using a prefab like I described above. So... you just want to show the quit window:
[SerializeField] private GameObject QuitWindow;
private void OnEnable() => QuitWindow.SetActive(false); // hide it at startup
public void DoAction(int actionType)
{
switch (actionType)
{
...
case 2:
QuitWindow.SetActive(true); // turn on the quit window
break;
case 3:
QuitWindow.SetActive(false); // turn if off
break;
}
}
The instantiate and destroy works correctly, the problem is that I cant put the play, settings and quit buttons interectable back again. And none of this buttons are in the QuitWindow
Well.. I'm telling you that your way of instantiate and destroy won't work more than once. 🙂
How are you calling action()?
The problem is likely more with how you're calling it since it seems as if the code in this switch statement is fine (if the buttons aren't nested under the QuitWindow)
Oh, I bet I know what it is.. Are you wiring up the buttons to this script's action method? If so... then obviously they won't work after you set them to interactable = false. 🙂
from here
yeah - so you're disabling the buttons in one call which means they can't trigger on the next button press
(and the int is fine for this instead of an enum, I didn't realize you were linking it up to unity that way)
Do you understand why it doesn't work now?
ik that when i disable them, they cant get triggered again, the idea is that with another button, i can enabled them again
not if that other button is disabled too..
it isnt
put some debug code in your method then:
public void DoAction(int actionType)
{
Debug.Log($"DoAction called with actionType:{actionType}.");
}
and at least make sure you're getting it called
can i send videos here?
it works
Sure, send video.. make sure to include the whole screen (+ inspector)
ok so back to my original statement.. the issue is that you're instantiate()-ing the new window. This is going to create a new instance of the window, and this new instance of the window isn't going to have correct pointers to the existing buttons
You don't want to use instantiate
When you create that new quit dialog, yes, it has a component of Buttons on it, but the references to your main screen buttons is.. incorrect
even though i added in the prefab if the window the prefab of the buttons?
Yes.. A good way of thinking about a prefab is that it's the design of an object, not the actual object. The design of the object isn't going to have references to the actual buttons in your scene (unless you link them)
What you really want to do here is create a quit dialog in your scene, and show/hide it using SetActive(true/false) each time you want to show it.. and in that dialog, make sure that the button is linked to the parent DoAction() script you made
I'm not sure how to explain it better - but basically you're creating a new instance of the quit dialog, which won't point to the buttons you're trying to enable/disable
i understand that
now, if i do quitWindow.SetActive(true); it doesnt show it
did you add it to your scene and link it in the inspector?
yes
(to each button)
yes
video it and show me
you linked to the prefab, not the instance in your scene
quitWindow shouldn't be a prefab
in general, don't create prefabs unless you're making more than one of something .. I can see that this is sort of confusing you, so you might just be better off not making any prefabs at all
still doesnt show it
Video again
In any case, I think you can figure this out - but you need to get up to speed on what an instance is, what a prefab is, and make sure that your scripts are "pointing at" the correct objects, because your bug right now is that they aren't.. I'd even stay away from using prefabs and Instantiate() entirely until you understand this a bit better.. You can find more help in #archived-code-general or #💻┃code-beginner , we're clogging this channel up a bit and this is definitely not an advanced question. 🙂
the buttons also shouldnt be a prefab?
They could be but not until you understand prefabs better 🙂 Putting all of your logic in one script called Buttons isn't correct
ok, understandable, tysm for ur help
I have a large mesh (could be concave or convex), with two 'random' points on it. I am trying to figure out how to get a path along the surface of the mesh from one point to the other.
Any thoughts of a good way to approach this?
For added context, the mesh will be cliffs, overhangs, etc. And I want to place objects along the path for the player to walk on to traverse the cliffs/etc.
Well a naive solution would be to just have a line above the mesh
And then raycast down every X amount of units
Depends on how precise you want your path to be
Oh that wouldn't work for the overhangs
Maybe if you get a lil bit fancier with the raycasts it would still work
I am using graphics.Rendermesh to draw, 4 mesh chunks.
However, the chunks positioning seems to be off. If you take a look at the picture the chunks positions are suppose to be at the position of the green sprites you see.
Anyone know why they are so far off?
nvm, figured it out 🙂
Anyone have any ideas for tweening a nice little "drop" in 2d (don't have access to gravity/physics because I'm doing this in the UI layer)? I tried an animation curve with a parabola but it looks pretty janky to me.
linear x and animationcurve y (from 0 to 1 at 0.5 back to 0 at 1)
maybe i just EaseIn it in a random circular direction
The sudden stop of the animation is jarring. It also does not feel right. I would try to find an alternative for that:
- Make the object go all the way. (Then maybe add a secondary window for the object that has been accumulated)
- Add particles effect to ground the object.
- Make the object fall in between the cells.
- Maybe try to have a more isometric view or have a more top down view/movement. At the moment, the movement feel out of place with the rest of the esthetic.
things like Vector3.Slerp and Lerp will help you smooth out your movements and make it less janky, u can do alot with them in terms of animations, i always use it when doing any animations in code
I already have a tweening library.. I was more asking for some good looking tweens since I'm an animationoob. 😛
Here's what I settled on for now:
just straight out on unit circle with OutQuint over 0.6 sec
i like the numbers poppin, looks good
thanks.. pretty old piece of code that I use in almost all my projects.. happy to share if you want it
sure share it why not
public class HitText : BetterMonoBehaviour
{
public Color StartColor;
public Color EndColor;
public TextMeshProUGUI Text;
public int MinX = -30;
public int MaxX = 30;
public int MinY = 50;
public int MaxY = 70;
public void ShowAndDestroy(string text, float duration)
{
gameObject.SetActive(true); // in case the a renderer is using a disabled prefab in the scene for color customization etc
Text.text = text;
Text.color = StartColor;
Vector2 newPos = new(transform.localPosition.x + NumberUtils.Next(MinX, MaxX), transform.localPosition.y + NumberUtils.Next(MinY, MaxY));
Sequence seq = DOTween.Sequence();
seq.Insert(0, transform.DOLocalMove(newPos, duration));
seq.Insert(0, Text.DOColor(EndColor, duration));
seq.AppendCallback(() => Destroy(gameObject));
seq.Play();
}
}
NumberUtils.Next() just gets a random float between min/max, so you'll have to replace that with however you get randoms
(I feed all my calls through my own numberutils for seeding/testing reasons)
oh also, change BetterMonoBehaviour to MonoBehaviour.. i have my own stuff in there
Home made Monobehaviour 😄
heh, yeah
thanks 🙂 il have a look
i overrode Destroy() because I wanted it to fail if I used it on a component instead of a gameobject (I never destroy components, so if I do, it's a bug)
because of GC?
No, because I just .. don't really assemble my gameobjects at runtime, so I don't use Destroy that way
if I call Destroy on something, I want it to kill the GO, not the component
oooh didnt see "is not GO
like this would be a bug for me:
private HitText MyHitText;
private void SomeMethod()
{
Destroy(MyHitText); // doesn't actually destroy the GO - just removes the component from the GO
}
with my code, the above will throw an assertion failure
well good thing u can do stuff like that to customize it for urself, i honestly always test everything even if i just added a new particle system so i know if something is wrong
It'd probably be better to make an analyser that detects this instead of having a method and required inheritance
Hm, that's an idea. I've never written my own analyzer. Good evening project, I think.
Neither have I, it seems like a good usecase though
I also have some other stuff in that class.. extension method DestroyAllChildren() too since it's something I do often-ish
You can move that stuff to actual extension methods or static methods
oh, fair.. I actually don't think I have anything else (anymore) in my MonoBehaviour so if I wrote an analyzer for the Destroy() thing and then moved all the extension methods just to MonoBehaviour I'd be done
Imo it'd make sense for DestroyAllChildren to be an extension of Transform, and the All is probably redundant
hm, perhaps.. I tend to not think of a transform as separate from a GO though.. like, to me, the GO is "the thing".. I don't think of children as properties of the GO's transform, if that makes sense? It's just my own mental model
I mean, my code knows 😛
public static void DestroyAllChildren(this GameObject gameObject)
{
if (gameObject == null) return;
for (int i = gameObject.transform.childCount - 1; i >= 0; i--)
{
UnityEngine.Object.Destroy(gameObject.transform.GetChild(i).gameObject);
}
}
probably not the best function since I imagine internally childCount needs to enumerate them
but I don't do anything with millions of GOs so my O(n^2) loop is insulated with the Power Of Small Data Sets
reducing triangles count results in zero gains in FPS?
unsafelist cannot use pointer as generic parameter but i realized that i can cast the pointer to ulong.... have anyone did this before? i wonder if it is safe
Maybe your constraints lie elsewhere.
and i try to wrap the pointer into a struct, work...
Reducing triangles would only help you if you have a GPU bottleneck. And most mid-tier modern GPUs wouldn't have a problem with several million triangles. You're likely CPU bound. You'll need to use the profiler to learn more on the issue.
The first step of optimization is to use the profiler to identify your bottleneck.
If you're not optimizing your bottleneck you aren't going to see any gains
Using IntPtr is safer for casting pointers, as it will match the size of the platform architecture.
I have an AnimationCurve variable on a ScriptableObject exposed to the inspector, once I edit it in the inspector, how do I copy the values as code? I can only get them in a JSON format. Any help is appreciated thanks!
What are you trying to do exactly?
Once I define a AnimationCurve variable in a script, I edit it in the inspector using the graph editor. What I want to do is be able to copy the values of the graph as code so that I can define it graph in the script itself.
public AnimationCurve curve = new AnimationCurve(the curve value that I can paste as C# code in the script);
what do you mean by 'as code' an Animation Curve is data not code
by code I mean data essentially that is compatible with the c# script. For example if I define a vector2 and edit it in the inspector and I right click the variable and copy, I get this
Vector2(0,0.660000026)
I can paste this directly into the code for the variable value and it works (with a few modifications)
public Vector2 vec2 = new Vector2(0,0.660000026);
the AnimationCurve is copied as JSON data which I doubt can be used to set the variable's value
AnimationCurve JSON data below
UnityEditor.AnimationCurveWrapperJSON:{"curve":{"serializedVersion":"2","m_Curve":[{"serializedVersion":"3","time":0.0,"value":0.0,"inSlope":34.68950653076172,"outSlope":34.68950653076172,"tangentMode":0,"weightedMode":0,"inWeight":0.0,"outWeight":0.031713906675577167},{"serializedVersion":"3","time":0.105804443359375,"value":1.0,"inSlope":0.8033333420753479,"outSlope":0.8033333420753479,"tangentMode":0,"weightedMode":0,"inWeight":0.08614794164896012,"outWeight":0.0}],"m_PreInfinity":2,"m_PostInfinity":2,"m_RotationOrder":4}}
do you mean this?
https://docs.unity3d.com/ScriptReference/AnimationCurve-ctor.html
Yeah
still not sure why you need this. The AnimationCurve is in your SO so just reference or copy it from there
I need to hard code it into the script because the AnimationCurve value is not retained when copying to new projects (or publishing as a draft in publisher portal as an asset)
you dont need to hard code anything.
If you serialize the KeyFrames into an SO and distribute that so then you can rebuild the AnimationCurve from that
What do you mean by serialize the KeyFrames?
make a SO with a public KeyFrame[] and copy the keyframes from your animationcurve into it
if DoSomething have to read the z property of the void*, i have three options to do this:
- cast the someStrust pointer to (int*)(someStruct+(k<<2)), fastest way but no one use it since you have to guarantee the z property must at fieldoffset k<<2
- declare interface and change the DoSomething into DoSomething<T>where T: someInterface
- pass copy z to it but not work if the function will write the z property.
obviously 2 is an easier way to this but i hate function call just for few lines of code (getter setter are function calls to only one line of code in this case), though AggressiveInling can prevent it but you cant guarantee the compiler must inline the code.
You can just do (*(A*)someStruct).z, no?
Yeah, but you don't need to deal with field offset.
I have no idea, what the problem is
I had a friend pull this off
why cant I?
Looks like all ur time is currently being spent rendering, based on the screens shot I can't tell really what your rendering, but there is likely a more performant way, like gpu instances, or merging static meshes, etc.
im using Graphics.rendermesh
If yoyr rendering a bunch of the same type of mesh or something, using https://docs.unity3d.com/ScriptReference/Graphics.RenderMeshInstanced.html this or something similar can be way more performant also if your mesh has a bunch of different materials that can slow things down a lot
they are all going to be different
You can get really fancy ans provided what your trying to render works with it, using a compute shader then a custom material that renders the output buffer of it directly can be insanely fast, like I'm taking 10,000,000+ particles in real time, or creating huge marching cubes rendered scenes at 500+ fps, etc. But that solution won't work for all usecases
If they are all different you may need to look into other performance fixes like culling if possible, or using more basic shaders
What are you rendering?
Are they all on a flat plane?
for now yes
Creating a tile able hexagon texture then using a texture that packs the type of hex into rgb channels or something would probably render really fast. Depending on how many unique materials your using, you could probably render it this way quite efficiently
huh
If each hexagon is of some type, like for example if it's being used for terrain, u could make a sprite sheet with each type of material in a square, grass, lava, rock,etc like how minwcraft does it, then just have each hex color point to the material in the sprite sheet
Well it seeing caused by rendering in the profiler graph you showed, like 90% of the frame time was rendering
Here is the build
that was others
Here is a better look
Oh in this graph ur rendering is only like 10% of the frame time
Looks currently cpu bound based in a higher cpu time than gpu time
If you reduce the hex count until you can render at around 100 fps, then turn on deep profiling it'll give you a better breakdown as to where your cpu is spending its time. The reason for first reducing the hex count is that deep profiling is very taxing and causes everything to run really slow, and if your already at 30 fps, if will be super slow and not very usable
but based on the video, shouldnt I be getting much higher fps
Tbh in that video I didn't know what I was looking at, but if it's cpu bound, doesn't matter what your drawing you can still have low fps
that json should work, specifically that array you copied inside, this part
[{"serializedVersion":"3","time":0.0,"value":0.0,"inSlope":34.68950653076172,"outSlope":34.68950653076172,"tangentMode":0,"weightedMode":0,"inWeight":0.0,"outWeight":0.031713906675577167},{"serializedVersion":"3","time":0.105804443359375,"value":1.0,"inSlope":0.8033333420753479,"outSlope":0.8033333420753479,"tangentMode":0,"weightedMode":0,"inWeight":0.08614794164896012,"outWeight":0.0}]
Should be able to serialize that, I think, to an array of KeyFrames, but Im not sure if Keyframe has a paramaterless constructor
that was a 500 x 500 hex being rendered, its just zoomed out
Oh gotcha, one easy tweak would be to render the hexes to a render texture, then just render it as a cheap set of quads. You could update the render texture if one of the hexes within it changes, and to support an infinity sized world, you could recycle the render textures so you only keep a handful of them allocated, and as the hex grid pans off the edge of the screen use that same texture for the hexagons coming onto the other side of the screen, etc.
Rendering every single hex every single frame even with gpu instances, etc sounds sub optimal if they can easily be represented by a much easier to render method like a render texture
Ok
Next step is the frame debugger if you determined that rendering is the issue
Ah this is a super slow way to render a ton of meshes
Look into Graphics.DrawMeshInstanced / Indirect
All the meshes are distinct, so I cant instance them
So I have a large pseudo INotifyPropertyChanged class implemented, its actually multiple classes nested in a tree. These represent my game state.
And example of one of their properties looks like this:
private int _roundCount;
public int RoundCount
{
get => _roundCount;
set => Mutate(ref _roundCount, value);
}
the Mutate method both sets the value of the backing field and automatically fires off the PropertyChanged event that is being listed to be subscribers.
Current challenge: I want to be able to deserialize saved game data to this class. Aside from having to manually go through and write a bunch of code that sets every single property, what other options do I have? Roslyn Postprocessor perhaps?
I havent chosen what I want to serialize to yet, could be protobuf, json, or a sqlite DB locally saved, its not important.
The big challenge is I need to "load" all that data into this game state, but then I still need to actually fire off all of those "PropertyChanged" events so all of my listeners will actually load the data
One thing I have considered is, perhaps, adding 1 additional event that everyone can hook into that is an overarching "total reload" event, and all the subscribers know to just do a total reload with their respective methods when that one fires off
Just as an example of one of my services, this is how my subscribers function atm:
public void Initialize()
{
BindGamestate();
RedrawActionButtons();
}
private void BindGamestate()
{
GameState.BindTo(s => s.RoundCount, OnRoundCount);
GameState.BindTo(s => s.UI, RedrawActionButtons);
GameState.BindTo(s => s.Abilities, RedrawActionButtons);
GameState.BindTo(s => s.SceneState, ClearHighlights);
GameState.BindTo(s => s.UI.SelectedAbility, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.HoveredAbility, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.SelectedTile, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.Submitting, RedrawPlayerHighlights);
}
I could perhaps add one more listener thats along the lines of simply
GameState.Reloaded += OnGameStateReload;
Which will call both RedrawActionButtons and RedrawPlayerHighlights, as an example
My game has a different reactivity system, which is modeled closely after Vue’s. Perhaps you can find some idea from it.
The atomic unit of reactivity is Dep<T> and T could be anything, an int, a Texture2D, a GameState, whatever. It doesn’t need to implement any special interface or anything.
That part is fine, the reactivity works.
Issue us when I load data from file, applying the model to the viewmodel and triggering all the "property changed" triggers
A Dep<T> could be watched (when the value changes, notify subscribers), could be derived into another Dep<T>.
A level above is Ref<T>, which allows you to change the value, and causes Dep<T> to notify all the subscribers.
Make your deserializer use property setters 😄
So for game state, it would be managed like this:
private Ref<GameState> _state = …;
public Dep<GameState> State => _state;
(So that outside cannot mutate the game state, only this class can)
And if an exp bar UI for example, only cares about the exp, they could write:
Game.State
.Computed(state => state.exp)
.Watch(exp =>
{
// Exp changed, do something
});
Here’s the critical difference between this reactivity system versus yours: data owner does not determine what events exist and when they need to be raised, all data owner does is just changing the value.
Subscribers decide what part of the data they care about and derive new Dep<T> to represent it, and watch it.
This means your original problem doesn’t even exist in this reactivity system: the game will deserialize the entire game state at once without triggering any subscribers, and just set it:
var newState = LoadGameSave(…);
_state.Set(newState);
At the point of setting the new state, exp bar will be notified if exp changed, and nothing if not. Your subscribers will never run into issues such as “game state is in a partially deserialized state and contains illegal conflicting information.”
(This reactivity system is also nice that there’s zero boilerplate writing all the property change events)
That's the part I'm surprised by. How are you able to notify everyone in _state.set(...), without needing to write code for every member individually?
Because Dep<T> keeps track of a list of subscribers, when you write:
Game.State.Watch(state => …);
That lambda is added to the subscriber list. And when state is changed:
_state.Set(newState);
It runs all the subscribed lambdas.
does anyone know any good videos to learn how to code and do stuff on unity
it doesnt have to be videos
but i prefere them
What's the norm when people are using addressables but wanting to do non-async loads and instantiations? Would it be OK practice to for example load a prefab via addressables that has a bunch of serialised asset references (e.g. EnemyAssets.prefab) and using that reference doing regular:
EnemyTypeA = Instantiate<EnemyTypeA>(EnemyAssets.TypeA);
?
Trying to update my oldschool Resources.Load habits (not that they don't work fine in small games), but doing every tiny non directly serialized instantiation via an async workflow seems crazy.
This reactivity system isn’t just limited to managing game state either, you can very well make one single dep for managing the game time:
private Ref<float> _time = new();
public Dep<float> Time => _time;
private void Update()
{
_time.Set(UnityEngine.Time.time);
}
And everywhere else that needs to update every frame can just watch this and use it to drive logic. In fact, those code don’t even need to know they are in a Unity game, all they need is just the Dep<float>.
If you wan something to happen only once per two seconds?
Game.Time
.Computed(t => (int)(t / 2))
.Watch(() =>
{
// Triggers once per two seconds
});
Hello everyone, I am creating a weapons system for an fps game that I am making, my idea is to create a weapon stats tool that allows generating a recoil with a curve, I have solved that part a bit, but I have a specific question It's that I want to be able to make the weapon move with code and not with animations, I want that when configuring a curve the weapon moves forwards and backwards depending on the curve settings, that's possible, I'm not saying give me the code , only if you have any information that can help me that would be great.
What exactly you are looking for ? Because, yes, you can have code that serves as "animation".
What is your current issue ?* Why can you not implement it ?
is there some who can help me
I'm sorry if I didn't know how to explain myself, I want to know if it is possible to make the recoil animation of the weapon with code through a curve
Yes.
Do you have any information, guide or video that can help give me an idea of where to start?
Guide, Video, no. Information, it depends on what you want for information.
Why arent you able to simply "code" the recoil ?
Ideally, you would use Inverse Kinematic to make your gun. The recoil can simply be a change on the target of the IK.
My problem is that I have tried to implement the recoil curve of the weapon trying to make the movement directly on the transform of the object, when I keep the mouse click pressed the weapon moves in its z axis in positive and negative values, but I can't generate a really fast movement and a little more realistic for the recoil of the weapon.
You could even not use IK, and simply code the offset of the trajectory.
So, your issue is more about how to make a realistic movement. I'm not really an expert in such domain. I can help in code part, however, I wouldnt know what to do to make it realistic. Personally, I would do trial and error, look at what other games has done and ask other people (Not necessary programmer).
Also, I fail to see why you are not able to make a fast movement. You can literally teleport the transform to the position you want.
I would like to do it with programming, for later this tool generates the backtracking procedurally, but for the moment I will continue investigating elsewhere, thank you very much for your time.
Ah, my issue is I have my subscribed lambdas as passing the value into the reciever that was changed, so I dont have to manually fetch it, I think thats the problem perhaps.
private void BindGamestate()
{
GameState.BindTo(s => s.RoundCount, OnRoundCount);
}
private void OnRoundCount(in int roundCount)
{
...
}
So I would need to actually pass data into the methods I guess
I also have the issue where I can have multiple of the same method subscribed to various property changes, as it depends on many of them.
IE:
GameState.BindTo(s => s.UI.SelectedAbility, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.HoveredAbility, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.SelectedTile, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.Submitting, RedrawPlayerHighlights);
This would call RedrawPlayerHighlights four times if I just blindly fired off every lambda repeatedly D:
🤔 Not sure that’s the issue, my watch has 4 overloads, one takes a plain action, one takes an action with one parameter of current value, one with current and old value, and last one with both values + a bool indicating whether it’s first invocation or not.
For your second issue though, in mine I just make a new computed that just returns a tuple of those 4 values, and watch that so it’s only triggered once.
But really, your reactivity system is equivalent to mine just with different code organization.
I believe the core issue is that your game state being split up into multiple properties even though those properties are inherently linked together, causes subscribers to run at times when your game state is only half way updated and in an invalid state.
You said they were hexes
Ah for that I have a solution, I can open transactions to mutate the state, then commit the transaction and fire off the events (hash'd so unique only) all at once
@scenic forge So I think for now though my plan is to just have 1 extra simple event that can be subscribed to, that is simply "Game Loaded", and leave it up to the consumers to handle what to do when that occurs.
Yeah, that’s effectively bundling the entire game state as one reactive unit.
I don't know if this is the right place for this, but looking through the channels I don't anywhere else.
I am simply trying to diagnose a startup crash in a built project (Windows). I have enabled a dev build with PDB files and script debugging, and set the application to wait for me to attach the debugger. I am using Visual Studio for the debugging environment.
Attaching the Unity Debugger to the process is simply not working. I can see the application and attach the debugger, but once I press OK on the popup asking me to attach a debugger, the game simply crashes as normal and the debugger detatches itself.
I know that a breakpoint exist in Unity's code because I can use Visual Studios Attach to Process option and it picks up the breakpoint. However, with this I don't get any useful information from the call stack such as local values or parameter values. I was hoping using the Unity Debugger would rectify this issue (but maybe I am mistaken).
Here is a link to a video showing the issue.
I should have been more clear,
The hexes are made of meshes, then they are combined into chunks ...sometimes 100 x 100
then these chunks are rendered
Just an update to my enquiry few days ago about adding something to my game to allow me to add 500+ zombie prefabs to my game with smooth fps in WebGL.
I was able to do so and runs a good 60fps + 😀.
Try looking at the callstack and other running threads when the debugger is attached.
I've tried in one of the threads where the breakpoint gets triggered. The problem is I can't see anything besides the method names and parameters types in the call stack. I don't know if I'm missing something and that's why the parameter values and other local values aren't showing.
I'll try checking other threads I guess. Thanks!
It could be due to optimizations or the code you're inspecting not having proper debug symbols. Hard to say anything without actually seeing what you're talking about.
Okay, so here's a little video showing what I'm doing. First, you can see the Symbol Paths I've defined in Visual Studio. Perhaps I've done something wrong here, however the module that all of the methods in the call stack are from (UnityPlayer.dll) has symbols loaded (can be seen towards the end of the video). I added the other folders where some of the PDB files for third party DLLs and other DLLs are stored, but I don't know if I did this wrong. As far as I can tell, the debugger never loads these modules, like they aren't needed (maybe the crash is happening before they are needed?).
With the methods in the call stack there's not much I can do. It seems like this might be a serialization issue but I don't know what field from what class is causing issues. I would expect to be able to find that somewhere in the call stack. I'm very new to debugging however and fully expect I am doing something wrong or missing something.
It's pretty late where I am, so I look forward to seeing what you think in the morning. Thanks so much for the help!
Posted the above and then realized I need to double click the call stack methods to see the names and values of the parameters . . . still, the values I see don't seem to make much sense.
What you see in the callstack is all from unity C++ side. You won't be able to see the code and properties without getting debug symbols for the engine itself(which unity doesn't give out to anyone). Your best bet is to look at the log file, as according to the callstack, the error is printed there.
Hmm, okay, that makes sense.
The log files just says the scene is corrupted. I was hoping to get more information about what is actually corrupted using the debugger.
Does it open in the editor?
Yes
Were there any errors during the build?
Perhaps just rebuilding the game would fix it.🤔
Unfornately I've done several rebuilds. There are three errors during the build but they don't provide much information, and the build always succeeds still. I'll re-do the build so I can see what those errrors are again.
What errors?
Assertion failed on expression: 's.buildTarget.platform >= kFirstValidStandaloneTarget'
Any more details to the error?
no, but I did notice that the error occurs 30 times
it's called from UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
What's the actual stack trace?
it only shows in the Editor Log, not the console, but it's:
Assertion failed on expression: 'buildTarget.platform >= kFirstValidStandaloneTarget'
UnityEngine.StackTraceUtility:ExtractStackTrace ()
UnityEditor.BuildPlayerWindow/DefaultBuildMethods:BuildPlayer (UnityEditor.BuildPlayerOptions)
UnityEditor.BuildPlayerWindow:CallBuildMethods (bool,UnityEditor.BuildOptions)
UnityEditor.BuildPlayerWindow:GUIBuildButtons (UnityEditor.Modules.IBuildWindowExtension,bool,bool,bool,UnityEditor.Build.BuildPlatform,UnityEditor.Modules.IBuildPostprocessor)
UnityEditor.BuildPlayerWindow:ShowBuildTargetSettings ()
UnityEditor.BuildPlayerWindow:OnGUI ()
UnityEditor.HostView:InvokeOnGUI (UnityEngine.Rect)
UnityEditor.DockArea:DrawView (UnityEngine.Rect)
UnityEditor.DockArea:OldOnGUI ()
UnityEngine.UIElements.IMGUIContainer:DoOnGUI (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect,bool,UnityEngine.Rect,System.Action,bool)
UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect,System.Action,bool)
UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,System.Action,bool)
UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,bool)
UnityEngine.UIElements.IMGUIContainer:SendEventToIMGUIRaw (UnityEngine.UIElements.EventBase,bool,bool)
UnityEngine.UIElements.IMGUIContainer:SendEventToIMGUI (UnityEngine.UIElements.EventBase,bool,bool)
UnityEngine.UIElements.IMGUIContainer:HandleEvent (UnityEngine.UIElements.EventBase)
UnityEngine.UIElements.CallbackEventHandler:HandleEventAtTargetPhase (UnityEngine.UIElements.EventBase)
UnityEngine.UIElements.MouseCaptureDispatchingStrategy:DispatchEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
UnityEngine.UIElements.EventDispatcher:ApplyDispatchingStrategies (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel,bool)
UnityEngine.UIElements.EventDispatcher:ProcessEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
UnityEngine.UIElements.EventDispatcher:ProcessEventQueue ()
UnityEngine.UIElements.EventDispatcher:OpenGate ()
UnityEngine.UIElements.EventDispatcherGate:Dispose ()
UnityEngine.UIElements.EventDispatcher:ProcessEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
UnityEngine.UIElements.EventDispatcher:Dispatch (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel,UnityEngine.UIElements.DispatchMode)
UnityEngine.UIElements.BaseVisualElementPanel:SendEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.DispatchMode)
UnityEngine.UIElements.UIElementsUtility:DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel)
UnityEngine.UIElements.UIElementsUtility:UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (int,intptr,bool&)
UnityEngine.UIElements.UIEventRegistration:ProcessEvent (int,intptr)
UnityEngine.UIElements.UIEventRegistration/<>c:<.cctor>b__1_2 (int,intptr)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
weird. Try deleting the library folder and rebuilding. Perhaps there's some corrupted cache.
I tried that once before and it didn't work, but will try again. I think the project might be corrupted. At some points I am able to do builds, then I'll change a single script, rebuild, and it starts crashing again.
I appreciate the help.
I've got some other avenues to check; I was mainly trying to figure out the debugging stuff to figure out what I was doing wrong.
Now I know debugging is probably not the best avenue to approach this particular problem. That's appreciated!! Night!
I mean, this seem to indicated that your build is simply not being built correctly.
That error looks like it's just a Unity nUnit test that is coming back false.
What it thinks, for some reason, is that the platform you are building for is invalid
If I'm reading that log right
In vfx graph - why is texIndex using flipbooks is a float and not an int? I couldn't find anything in the documentation aside from the fact that it .. just is. https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@16.0/manual/Operator-GetAttributeTexIndex.html
Like, I'm assuming the behaviour is to truncate it to get the index, but I can't figure out why this is a float and not just an int to begin with... or is it just one of those "GPUs like floats" things?
Spent a few hours on this and gave up. Above my pay (brain) grade. Surprisingly lots of prerequisite knowledge required.. parsing syntax trees, mostly.
Yeah, but the question is why?
Question: If I multiply a vector with the Camera View Matrix (eitherprojectionMatrix * worldToLocalMatrix or worldToCameraMatrix), what is in w of the resulting vector? I'm getting weird values. I thought it was negative depth into the screen, but I get positive and negative values, all strewn about. It feels like clip space, but I'm not sure.
I see examples dividing by w, I need to divide by -w to get viewport coordinates that make sense.
Huh, an example uses _camera.projectionMatrix * _camera.worldToCameraMatrix , that's weird.
What kind of vector are you multiplying?
multiplying two matrices together "composes" them, giving you the result of applying one matrix then the other.
I'm not sure if this qualifies as advanced but I haven't been able to find anything online, in beginner, general, or the input system. I'm trying to get local coop to work with 2 xbox controllers specifically. I have each controller moving their respective player but only one controller is able to send input at a time. So if I hold fire on both controllers only the one that was pressed first will work. Any idea of there's a setting or something that needs to be done to be able to accept the input from both controllers simultaneously?
you are abusing Gamepad.current instead of following the actual recommendations in the input system for local multiplayer - which are to use PlayerInputManager and PlayerInput
when I tried using that before I wasn't able to find a way to get 2 gamepads working with it. I'll try to look through the docs again
the types of input devices don't really matter
before I did all this and was using the input manager it each gamepad would just move both players. I could get that to stop if I used like the keyboard and 1 gamepad @sly grove
You did something wrong then. That's the intended usage of that system
have you done it before?
yes
cool point me in the direction of some good info then because I've tried looking through the docs and following a few different tutoorials and have had 0 success
this is the closest i've come to it
the second player shouldn't even exist until you press a button on the second device or explcitly joined them based on your code
yeah that's what happens
did you set up your control schemes
same as if I were to spawn it with the start button using the input manager
when I was using the input mananger yes
If you're writing Gamepad.current, that's not using the system properly
okay this is what I did after I stopped using the input manger
you'd have to show what you did before
lol ok
World Space vector, want screen space position in normalized device coordinates [-1..1], at a time where I can't call managed code. I almost got it, but if the item is somewhat close to the camera (still about 2.5-5 units away from the near plane), I seem to get unexpected values for w (flips to negative early)
I'm aware of how matrices / affine mappings work, just... not exactly sure about what Unity keeps in these matrices. (and difficult to read apart from the trivial cases)
There is no w for a world space position vector. It should be a Vector3
You need to make it a float4/Vector4, you can't multiply a Vector3 with a 4x4 matrix. You feed in a Vector4 (set the last component to 1), then, you get a Vector4 back, where the w is normally known as the perspective correction; to get normalized coords, you divide by w. (only usually makes sense if one of the matrices is a projection matrix)
So yeah, that w... it's almost as if it's off by 1.
Manual says it should be negative, OpenGL style. It's only negative if I use the first matrix concatenation I gave, but not the newest one (which I took from another example - gives me nicer, positive values, based allegedly on Unity's internal code - but w still flips)
Positive or negative DX/OpenGL aside, I always thought w=0 means object is at the camera position.
Now I'm not so sure 😄
That doesn't work though, I have a 4x4 matrix. View matrix is always 4x4 i believe, and you can't leave a column or row off. 🙂
that's literally the docs for Matrix4x4?
Ah, I see. I can't call these, either - I have a float4x4, would love to see what they do. I'm sure they just append the w=1.
I can try to load a Matrix4x4
Huh, so this IS C#.
My decompiler said it was injected and I thought that meant it was in the C++ code.
Thanks, you're the MVP 🙂
Interestinggg. I think that's the same thing.
Oh, it's not. I should write down the 4*4x4 formula...
I think then "w" would be what w is here... + 1
No idea. I usually delete the library folder or revert the latest change when something like that happens.
Nope, it's the same. Good to know. They pretend their vector has a w=1 to begin with, so the last "this.m33" is multiplied by this implied 1. (as are all the last this.mxx terms)
I have the following error for some Burst Compiled Job Code. Anyone have any clue what this means?
Alright. I have a very specific inventory system I want to create so if anyone is willing to do some one on one assistance with me I would be very grateful. DM me if you are willing to help.
Try restarting Unity, if it doesn't fix it then try making a post in #1062393052863414313 where you'll have more visibility from those who might know
Okay, thanks!
hey, anyone know of any issues with C# boolean functions not playing nice with arrays>
im trying to play with some arrays inside of a bool function and im consistently getting null object exceptions when simply trying to access arrays that are working elsewhere in the script
im running this in an if function: itemModifier[0] != null
and getting an out of bounds exception from that
lol its not
I agree that under normal circumstances it wouldnt be but at this point im wondering if this isnt something deeper which is why its in here
Ive looked around the entire internet and ive found nothing.
Anyone here familiar with building unity projects using a docker image for CI/CD use case? Have a docker image they would recommend using?
Mostly for building targetting android
https://hub.docker.com/r/unityci/editor/ Should be reliable enough
thats the one I am checking out atm, looks like I will need to extend it to add automatic build functionality but, otherwise, it seems pretty good
Hey, I'm working on a Unity plugin and during the import process we add a scripting define symbol using
PlayerSettings.SetScriptingDefineSymbolsForGroup()
https://docs.unity3d.com/Manual/CustomScriptingSymbols.html
However, it seems that Unity/scripts don't recognize the define symbol until you close and reopen the editor. As a result some scripts don't work until you restart the editor.
I have tried a few things to trigger recompilation such as:
CompilationPipeline.RequestScriptCompilation();
Any ideas on how to approach fixing this?
We use that as a base as well
thanks, I have discovered that unity doesnt have an ARM64 version of their editor, so its gonna be a bit more of a pain for me to get it working with my kubernetes cluster build pipeline, smh
Hello everyone.
I want to add a "hook" before an attack to get the damage, as in, for example:
Attack comand -> GetDamage(from the player stats) -> run the hook passing the currentDamage (for things like damage amplifiers) -> execute the attack.
Right now I've set up a List of actions that ake in the information of the attack (Basically the currentDamage and if it's a crit):
public List<Action<float, bool>> beforeAttackHooks = new List<Action<float, bool>>();
Where if something needs to modify the attack damage it will basically add the modifying function in this action list.
Then, in the GetDamage function i run through all the actions:
bool isCrit = IsCrit();
float damage = characterStats.atackDamage.Value;
foreach(Action<float, bool> action in beforeAttackHooks)
{
damage = action(damage, isCrit);
}
My issue is that I can't seem to find any way to define these actions as floats intead of voids. Any ideas on how to make this work? I'm open to hear about enterily new aproaches, since I'm bringing the concept of hooks from web development and I'm not sure it's the best method to apply here.
You probably want Func<float, bool, float> looks like
Action is specifically a void, Func is the one that has a return value 🙂
Oh man I feel so dumb xdd thank you
my guess is that the AddForce function asks for a ForceMode and not a ForceMode2D
but it is a 2d game
no
Yes?
my game is a 2d game and i am using rigidbody2d
Well your code isn't https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
If it was then you wouldn't get this error
hahaha
Btw, for anyone that might have a similar issue or will in the futrure. The obious solution here is to use events, so that' what I've done, well, actually I've done both systems, but events are definetly the right solution here 🙂
How does that work? Did you just pass in a reference to damage in the action args
right 👍 events are great for this. very neat and intuitive. it does come with a problem however, and that is the ordering of the executing subsriptions. a
A += i => i * 2;
A += i => i + 1;
yields a different result than
A += i => i + 1;
A += i => i * 2;
so we'd need to implement some ordering ourselves if we want to have fine control over it
- also beware that if you pass an event itself as a subscription, (
A += a;), you're subscribing a copy ofa. so, further modification toawill no longer account forA. you can however pass a true reference ofaby doingA += i => a(i)
I dont think ive ever needed to actually do this, but if you need the return from every func I would just use GetInvocationList
Heya folks, here's a doozy I just hit in my game.
The setup:
The save system for my game consists of creating a json-formatted string, salting it, converting it to bytes with Encoding.UTF8.GetBytes(), converting it again with Convert.ToBase64String(), salting that string and saving it to a file. When the game loads, it unsalts, does Convert.FromBase64String(), does Encoding.UTF8.GetString(), unsalts again, and reads the json data.
The problem:
It appears that at some point in the loading process, Russian-language operating systems (this is reproducible on my own machine, even) have a problem and create a corrupted save. I have a couple ideas for how to further debug and may likely end up having to create some kind of sanitizer but I would like to know if anybody has thoughts on why this happens and a decent way of fixing it. Are there known issues with the functions I've mentioned and is there any way to set up Unity's Localization package to allow me to debug this without having to keep changing my Windows language back and forth.
yeah, will make a lot of boxing though if the parameters are value types.
Generally, lot of possible workarounds, none internally ideal, but at least it'll have a nice external usage 👍
I'd say that setting up a kubernetes cluster for your builds is kind of overengineering in the first place 
It really is not, depending on your scale
I dont know the scale at which you are working at but for us where we work on a single game as a fairly small group it rarely happens that multiple builds are queued
100+ people, multiple platforms, sometimes multiple platform configurations, tests, validation, probably more
Then it does not longer sound overkill
All those can be in parallel
But I don't think it's fair to assume the majority of people asking questions about game-ci in this discord do that
Possibly 😛
well yeah but the OP mentioned it themselves
I don't understand what the salting is achieving here. Usually it's used with hashing or encryption, because salting will make the output completely different. But since you're only encoding to UTF8 and then Base64, the string would be mostly the same, with some bits different wherever you added the salts.
Also dockerized builds can be really useful to deal with all those native SDK versions
I am not saying dockerized builds are bad
Bless, thought something got lost in translation somewhere x)
It's just 1 extra step someone hacking their save has to take to figure out how to hack their save. I'm actually gonna get rid of it because I stopped caring.
I can guarantee if the hashing was the issue, this problem would be happening in English too
You're not hashing here though, just encoding
I doubt it adds security? seems like converting it back to a string from base64 will just add some random stuff at the end
nah it corrupts the whole thing
but, again, pretend it's gone, I'll just let people figure it out
I dont think you should prevent single player cheating, you should maybe even encourage it
I guess depending on the character, it might mess with the UTF-8 encoding. But the first salt before encoding to UTF-8 does nothing.
Some players might think your game is too difficult or harsh and they might make it a little bit easier on themselves
Or the progression is too slow for them
well I have a DLC that makes it easier
So they skip ahead
if they really want to hack they can just cheatengine
but people buy the DLC so why not
none of this is answering my question though
But if the only answers anyone has available are "get rid of the salt" then gosh darn I sure hope that's what solves the issue and it'll be the first thing I try tonight. I just really, really doubt it's the issue.
I suspect it has to do with the conversion from and to UTF-8
I haven't really seen json serialization errors in the RU language, I guess it's possible but seems unlikely
as UTF-8 characters can be multiple bytes, so maybe it is messing up the conversion back to string values
Also, specifying a locale wherever you can is useful
I have no localization in this game and don't plan on managing it either. I did try to specify the (ru) locale using the Localization package but it did not reproduce the bug.
But that would mean the built-in utf 8 encoder / decoder is broken.. That doesnt make sense either
I had to change my windows language to russian to get a repro to occur
Is it just russian? or other languages as well; uk/us english use different decimal points
I have yet to test other languages and the only person reporting this bug is russian
I would like to test other languages but if it requires changing my windows language to do so, that's a bit rough! Would really appreciate unity's localization package to do the work needed
Perhaps it is a keyboard layout issue and not a language issue?
That would be interesting since I don't pull input for any part of the save/load process
That doesnt matter
Unity's localization package is just for managing text/image assets for different languages. Not low level encoding like this.
Okay good to know, thanks!
just doing a float.toString() uses the computers locale to do so
which means either , or .
depending on language
I doubt it's keyboard layout, it's probably locale which you can change for your app
That might get you to repro it without changing windows language
I will give that a shot right now, thank you!
You need to step through the whole process in both locales and see at which point the string differs.
For sure, I've already thought about this. I ended up creating a class called "Attack". Ended up using the Action<Attack> list for the hook and a BeforeAttack(Attack attack) for the delegate void of the attack.
Now if soe script wants to modify an atack before it's shot they can do thriough the Attack class, wich holds the info asweel as 2 methos: Damage from base, which does the damage modification, but allways parting from the base damage of the attack (hence eliminating the order problem) and the Damage from currrent, which is order sensitive, but I don't even think I'll even use.
Finally when the atack is actually shot it takes the damage stored in this class.
I'm a lil worried about memory alocaiton, since this class is usefull for exactly 1 fame, and never used or stored, is there a way to improve this?
@flint sage Thank you so much, that's exactly what I needed. Can now repro instantly.
My bad, I meant to say that there's multiple components to your locale, not just language
After I solve the problem, I'll have to shove all the locales I can through this, that'll be fun...
So since it's locale, it's probably your salt since I doubt the serializer breaks on RU
You might also want ot look whether youcan pass a locale to your serializer
And just pass the same to it so that it is consistent
Someone managed to reply to my forum thread with the suggestion I use myInt.ToString(CultureInfo.InvariantCulture) so now I've got something to try :)
Before I do anything I'm getting rid of the salt to see if that's really it hahaha
Had the dang thing since late 2000 it's so hard to believe it's taken this long for people to report issues
I always set the current culture to invariant
As you should
I never even knew this stuff existed until today
There have been too many games that run into issues with de/serializing because they don't do it, and the bugs typically manifest on cultures that use a different decimal separator than .
I've seen some high profile games getting hit by it.
Then I'm in good company haha
That's generally only an issue if you write custom serialization/converters
Bigger libraries tend to handle it by default if you use their api correctly
Given you use their API correctly yeah
It might not be the de/serializing step directly before saving/after loading a save, all it takes is one float.TryParse without the appropriate culture and you can have a bug sneak in, but yeah.
Confirmed, it's not the salting causing the issue.
But I'll just keep it off anyway.
It appears changing the culture to invariant fixes the problem
So is there any reason I shouldn't just consider that the fix?
Force invariant on everyone?
That would be the fix, but why are you encoding your own ints if you're using a JSON serializer?
So people can't look at their save file and immediately hack it
It doesn't take a lot of effort to hack but at least 1 step of obfuscation stops some subset of people
So are you using a json serializer, or not?
and if you missed it: the game has iap/dlc for skipping ahead and people pay for it, so preventing some level of save file hacking is needed
yes, I am
sounds nice. you can reuse the class to eliminate memory problem (maybe just add a Reset function), or make it a struct so it won't bother the garbage collector.
as for the algorithm itself, I think if all the expressions you'll use are multiplication and addition, then you can have like AttackBase, AttackAddition and AttackMultiplication, or even better, a new type just for this (so reusable for other buffs too)
public class BuffsCalculation
{
float _base, _add, _multip;
public void SetBase(float value) => _base = value;
public void Add(float value) => _add += value;
public void Multip(float value) => _multip *= value;
public float GetResult() => (_base + _add) * _multip;
// or
public float GetResult() => (_base * _multip) + _add;
}
and then instead of things subscribing to an event, they can just modify this right away. when they used to subscribe, they can Add(val), and when they used to unsubscribe, they can Add(-val)
(you can expand that to have like AddSpecialMultip etc for special expressions. like, in Witcher some skills indicate that they multiply over any previous calculations)
Hmm, really smart, I'll give it a try. Even if i'm goiung to just refact all of it I'm having an issue with it now I'df like to understand.
For some reason, having changed nothing, unity is giving me a NullReferenceException: Object reference not set to an instance of an object error with it.
This is not all the code, but the relevant part. (I can add more if necessary):
The line giving the error is the event call one:
//Event devlaration
public delegate void BeforeAttack(AutoAttack auto);
public event BeforeAttack OnBeforeAttackFired;
//In the auto fire method
bool isCrit = IsCrit();
float damage = characterStats.atackDamage.Value;
AutoAttack auto = new AutoAttack(damage, isCrit);
//Line that's giving the issue. Where auto is the said class.
OnBeforeAttackFired(auto);
Is the issue the event, or is it most probably the parameter auto that's missing or something?
even though OnBeforeAttackFired is not technically a field, it can still be null. it's always better if you do a nullcheck just in case
how could it be null tho, it's clearly defined no?
defined, but never been assigned anything. you can assign by subscribing something to it (OnBeforeAttackFired += someMethod)
aaah, okay, nevermind, I did comment that code to test somthing else ahaha, thank you very much
np ^-^ glad it's working
I've refactored it so it is only 1 autoattack that other scripts can add and remove damage, but I have added an event for onHit events since more than 1 auto can be out at the same time, with sufficient attack speed xd
Thank you so muich for the help!
clear
HAHAHAHHA
NO WAY
I should take a break lel
Hello! I've got a bit of a pickle, wondering if anyone has solved it in an elegant way
In unity 2021 I'm doing this during an SRP, because I need to check and do logic based on a mesh renderers shadowcasting flag
MeshRenderer[] meshRenderers = GameObject.FindObjectsOfType<MeshRenderer>();
This is kinda terrible. Is there a better way to keep track of all the mesh renderers in a scene (better still all the mesh renderers visible to a camera) so I can avoid the FindObjectsOfType?
No, SRP intentionally keeps this information hidden from the C# side.
The unity documentation suggests creating a singleton instead of FindObjectsOfType, but I don't control the lifecycle on them (gameplay people do gameplay stuff)
Oh. Rough. So I'm out of luck then?
Yes, it's either FindObjectsOfType or putting your own component on all the renderers to keep track of them.
Okiedokie. SRP is nice but it feels oddly limited in some ways
eg: Im having to do some hairy layer shenanigans to render out my own shadowmaps
Have you looked into how URP manages it? It has as much access as you do.
Yeah, it relies on the magic "make me a shadowmap" API
which unfortunately doesnt suit my needs
s'ok though, thankyou for confirming for me
Keep in mind the ShadowUtils api is still C#, should be possible to see what it's doing under the hood
Yah, my issue is I'm using my own lights and light class, so I can't call context.DrawShadows(), it has to be a regular rendering pass
so that means setting up my own culling and filtering
oh well, it's not too bad, I've followed MentallyStables suggestion of looping over an attached component instead
If you can put your culling results into a cullingResults object, and create a valid ShadowDrawingSettings struct from it, you should be able to call ScriptableRenderContext.CreateShadowRendererList to get the renderList you need
I have one of those, but I didnt think I could use CreateShadowRendererList because I am not using any lights in my scene
SRP seems to have this concept of lightIndex integers. I might have to create proxy light objects so I can use that functionality.
too much for me to tackle right at this moment ^_^
Lightindex in the URP source code seems to map to an index in the visibleLights array of a CullingResults struct. That CullingResults struct is passed in as a part of the ShadowDrawingSettings. That means so long as you create a culling results with the correct number of lights & associated data, the CreateShadowRendererList should have no reason not to work
As far as I can tell, the lightindex integer is nothing more than an index for CullingResults . That means you should be able to fabricate both the array it's referring to, and the index yourself without problems.
oh! is that so hmm...
Ah, no, I dont think that can work, because the cullingResults comes back from my shadow casting camera. It has a NativeArray of lights, which I can't call ResizeArray on, nor can I just set it to a new array.
ah well >_<' I guess if I wanted to go that route I could make a proxy light object, but I'm okay using renderingLayerMask shenanigans for now to remove the non shadow casters from the shadow rendering. (and material shader passes too)
the real issue was walking the whole scene every frame to map the cast shadows flags to renderingLayerMask flags, but thats been eliminated now
The kubernetes cluster isnt just for my builds haha, my entire home arrangement is running on it. Password manager, build server, git repo, my personal website, blog, a couple projects, security cameras, plex, kavita, and a few other bits and bobs XD
kubernetes is one of those things that is a decent bit of work to get up and running, but once it is running its super easy to add more stuff to it to run. If it has a docker image its usually just a couple minutes of effort to toss it onto the cluster and stand it up
so yeh, Im gonna take a crack at it and see if its possible for me to easily or not get a simple minimalist unity build server image to work, that just compiles the unity project APK and spits it out into an artifacts folder, which is conveniently also the folder a seperate FDroid server will be hosting so I can just click the update button on my phone to pull the latest install as I need
Why am I not surprised 😄
is it possible to change the texture between two points on an object?
so I'm trying to make a kind of torch where the area in between the rays that form the cone of light has another texture to the rest of the object
how could I go about doing this? would appreciate any help 😊
Either:
- UV mapping / texture painting the model
- Using multiple submeshes and materials
could you elaborate on this a little? really appreciate your reply!
Start you SKILLSHARE Free Trial Today:
https://fxo.co/Dblx
3d modeling & animation is all fun and games till you realize that you have to though a process called Uv unwrapping, I don’t think that a lot of 3d artists like it but it has to be done for the most part.
Visit our Website:
https://inspirationtuts.com/
in...
this really isn't a code question btw
more like #🔀┃art-asset-workflow
oh ok sorry about that then
I do not think Unity officially support docker. At least, if you look at the roadmap. (I know that some people has successfully used one though.)
It might also be something else then building.
how can I make the input return like a full 360 degree angle? because this returns 8 directions only (1,0,0), (1,.0,1), etc.
You mean euler angle instead of a direction ?
No, I mean now when I move I can only move 45 degrees between every direction. I want to move the whole 360 degrees
It is expected... ?
You are using a keyboad arent you ?
no
I'm using a ps4 controller
forgot to mention this
is there some sort of processor on the action
also would it not be a Vector2?
stick is only 2 axis
Is there way to call internal static method of public struct of package from my code?
Unity.Physics.ConvexCollider.CreateInternal
no, internal means it can only be accessed from within the assembly the type is declared in
what about reflection?
yes, you can do it with reflection
possibly something to do with your Inputs, provide us with the full script that is attached to your Player
@flint sage I just thought you might like to know that the problems I had are all solved and the crux of the issue came down to a float.TryParse call on the application's version number (which sent the code off to act like the save was from an earlier version, aka had a different format) so in the end, it's float.Parse (or tryparse) that breaks when locale is different!
😄
Hey all. I am trying to work with the Localization package for unity, but can't seem to find how to do it for the newest version.
public LocalizedStringTable localizedTextTable;
So i am assigning the table I setup, but can't figure out how to get a specific string, using the active locality of course.
Do I have to do GetTable() and then get an entry from that?
Is it possible to create a variable type similar to Vector2 but instead of position numbers lets you enter a string and an an int?
alrighty so i got a weird problem i ran into.
even though i've set my texture2d to be readable, the sprite in the gameobject refuses to be readable.
im assuming the texture that it's using is elsewhere i cant see.
is there anyway i can change the sprite renderer's sprite to be readable while using code?
perhaps it's a duplicate in ram somewhere?
my guess is it's in a sprite atlas
Savage 😂
I don’t have the most experience but just create a class that does not inherit from anything, eoth a public int and a srring, then simply add a constructor and violá
Hi. Has anyone ever used a PID controller in Unity before please? Because I'm having a problem where I want to like lerp the value it outputs (so it feels like more smooth movement) but I don't know how to do it so the PID controller doesn't break and stops doing what it's supposed to do 😦
Don't give the PID back the smoothed position. Let it modify it's own position, and use that position as the target position for your smoothed value.
I don't give it back the smoothed position, I think that's the problem. Like, maybe explaining what it is for will make it more clear:
I have an aircraft with "realistic" physics (it rotates depending on the angle of the control surfaces and everything and not just by some simple torque applied), and I want it to like point towards a direction.
The values that the PID controller gets are the angles between the forward vector of the aircraft and the relative direction from the aircraft to the point I want it to look at, so that is something I can't smooth
The PID controller outputs the angles that the control surfaces have to be, so if I remove the lerping it kinda works fine, but once I add the lerping to smooth it out it stops working, and I'm guessing it's because the PID controller is guessing the control surfaces should be at for example 20 degrees when in reality they are at 10 degrees rotation because of the smoothing
I don't know if I'm explaining myself
PID controllers already smooth things
It seems like your PID controller is under the impression it can instantly change the control surface
and how do I smooth it even more because they feel instantaneous?😅
yeah
the control surface change is instantaneous but the aircraft's response to that is not, right?
the control surface change shouldn't be instantaneous either, but the only way to make it work is if I set it to instantaneous (so remove the lerp/no smoothing)
basically the PID controller needs to be reworked so it's aware of its limitations WRT how quickly the surface can be changed.
and how can I do that please?😅
right now your target variable is the orientation of the aircraft and the PID's input is the control surface angle.
You need to rework it so the target variable is the desired control surface angle and the input is the "voltage" it applies to change the surface angle. e.g. "tilt up/down" or whatever.
Impossible to say really since I don't know the details of your PID controller
It's not going to be super simple, it's kind of like - you're trying to achieve a certain thing but your input is two degrees of separation away from it
maybe it's just that you use two layers of PID controllers?
This is basically the PID controller I'm using:
float AngleDifference(float a, float b)
{
return (a - b + 540) % 360 - 180; //calculate modular difference, and remap to [-180, 180]
}
public float UpdateAngle(float dt, float currentAngle, float targetAngle)
{
if (dt <= 0) throw new ArgumentOutOfRangeException(nameof(dt));
float error = AngleDifference(targetAngle, currentAngle);
//calculate P term
float P = proportionalGain * error;
//calculate I term
integrationStored = Mathf.Clamp(integrationStored + (error * dt), -integralSaturation, integralSaturation);
float I = integralGain * integrationStored;
//calculate both D terms
float errorRateOfChange = AngleDifference(error, errorLast) / dt;
errorLast = error;
float valueRateOfChange = AngleDifference(currentAngle, valueLast) / dt;
valueLast = currentAngle;
velocity = valueRateOfChange;
//choose D term to use
float deriveMeasure = 0;
if (derivativeInitialized)
{
if (derivativeMeasurement == DerivativeMeasurement.Velocity)
{
deriveMeasure = -valueRateOfChange;
}
else
{
deriveMeasure = errorRateOfChange;
}
}
else
{
derivativeInitialized = true;
}
float D = derivativeGain * deriveMeasure;
float result = P + I + D;
return Mathf.Clamp(result, outputMin, outputMax);
}
So:
public float UpdateAngle(float dt, float currentAngle, float targetAngle) what are these inputs and outputs?
are these angles of the aircraft's orientation?
or of the control surfaces?
pitch = X_PID_controller.UpdateAngle(Time.fixedDeltaTime, XcurrentAngle, 0)
they are angles of the aircraft's orientation
and then that pitch is what determines what the angle of the control surface is
so the output is the new orientation of the aircraft?
and the control surface angle is determined by the difference between the current orientation and the new orientation?
the input is the relative direction to the wanted point to look at and the PID output is a value from -1 to 1 that is later multiplied by the control surface max angle so it rotates what's needed. But the problem is that it has to rotate instantaneously in order for it to work
right otherwise - it might be too slow to react
and the values are garbage
and you will get oscillation etc
if only there was a way to like limit the max change rate of the PID values internally
exactly
ok so... video game question here
you want the control surface change to not be instantaneous for realism?
exactly
Would it be awful if you mechanically changed the control surfaces instantly but just added some visual interpolation?
I mean I guess I could fake it and like set the physics control surface to change instantly and let the mesh object rotate smoothly, but idk
yeah exactly
the problem I encountered with that is sometimes it changes so quickly that it rotates the control surface so much that it becomes an airbrake😅
ah yeah that will not feel very realistic
this is not an easy problem
I have no idea how the people who make real airplanes deal with this lmao
and I've recently tried the visual interpolation but I'm not sure how to lerp the rotations as they are all local
some math and physics PHDs needed
yeah haha
you can just use Quaternion.RotateTowards as a simple basis
with transform.localRotation
yeah but the problem is that the physics control surface doesn't have the same parent as the visual one, so I can't use the local rotation in order to get the physics control surface (I think), and there should be like a rotation offset because their rotations are not the same at the start
like I used to just use the parent constraint, but that doesn't smooth it😅
~~okay fixed the visual thing after a lot of trial and error because I still don't understand quaternions at all: ```c
transform.rotation = Quaternion.Lerp(transform.rotation, RotationFollowPart.rotation*Quaternion.Euler(StartRot), Time.deltaTime * LerpSpeed);
the startRot is the rotationOffset and the RotationFollowPart is the physics control surface~~
Edit: Nvm it doesn't work lol
For lerp, you should cache the start and end state, then adjust T to go from 0 to 1. I didnt exactly read all context above, so I dont know if lerp is needed but that might be one source of unexpected outcomes
Everything works except the rotation offset. It does rotate as it should with smooth movement and all, but the offset is incorrect for most control surfaces
Edit: Now it works, the problem was the rotation offset because I was getting it with euler angles and not with quaternions lol
How do I make sure two assets don't go into the build no matter what? Those are generated on runtime and they only exist in editor time to save time
They are already in an editor folder
Used Assets and files from the Resources folder, sorted by uncompressed size:
122.7 mb 6.7% Assets/Editor/GeneratedAtlas/atlas NRSM.asset
122.7 mb 6.7% Assets/Editor/GeneratedAtlas/atlas ALBH.asset
If they're included in the build it's because something in one of your scenes is referencing them, or something in a Resources folder
Try HideFlags.DontSaveInBuild
Does not work unfortunately, it complains instead of omiting it from the build
An asset is marked with HideFlags.DontSave but is included in the build: Asset: 'Assets/Editor/GeneratedAtlas/atlas NRSM.asset' Asset name: atlas NRSM
despite being saved with HideFlags.DontSaveInBuild rather than HideFlags.DontSave
I think i need to use a source generator to do something I'm thinking about, but some microsoft websites say to use Incremental generators. Does anyone know about using these in unity?
does anyone know how to fix a problem where my walking animations is preventing my character from rotating?
Install the Microsoft.CodeAnalysis NuGet package. Your source generator must use Microsoft.CodeAnalysis 3.8 to work with Unity.
IIRC incremental generator is usable since 4.0. You can’t use incremental sourcegen with Unity.
Why are they not updating documentation 🤦♂️
What can I do about this massive time spent in Physics.UpdateCloth? This is for 6 horse reigns (with some capsule colliders for their necks/heads
Follow-up question: If I use a SourceGenerator instead of an IncrementalGenerator, will my build times take a lot longer?
I have the following scenario:
On Day 1, I create a Windows Build of my project. I can launch the Player without issue. I shut down my computer and the next day (Day 2), start it, open the project, and rebuild the project, having changed absolutely nothing (I cleared the output build folder before rebuilding). Now when I launch the Player, it immediately crashes.
My question is, where should I be looking to diagnose this crash? What could possibly change between a project from one day to the next from simply shutting the computer down!? Because I promise that I have not made any modifications to the project at all on Day 2.
what kind of crash are we talking about
like the unity editor crashes?
No, this is in a build when launching the game's .exe
so again
Player log says level0 is corrupted
what kind of crash
the app jsut hard crashes and quits?
It freezes?
It runs but brokenly?
yes, it hard crashes, the crash handler is displayed for a second
check the player logs
first make sure you're making a development build
and then check the player log
it usually happens on the splash screen
Log location is described here:
https://docs.unity3d.com/Manual/LogFiles.html
I have already checked the logs, as I said it says level0 is corrupted
The file 'E:/Bird_Sliced_New/Skara_Birdmen_Data/level0' is corrupted! Remove it and launch unity again!
[Position out of bounds!]
Crash!!!
Yes, level0 is the first scene in a build
but it happens with different scenes, so I don't believe there is actually a problem with the scene
as I said, one day it works, one day it crashes, without any changes
so I really don't think there is an issue in the scene
I would do this:
- open the scene in question in the editor and test it.
- if it works there, delete your old build and make a fresh build and test again
Thank you, but that does not work. There are no issues in the editor, the scene loads just fine there.
Really, my question is focused on how a project could possibly build fine one day and then not build correctly the next, when there were no changes between the builds on each day. Like, what could change in a Unity project between computer shutdown/start that would cause that?
And yes, I did try to rebuild after testing in the editor.
using the Clean Build option even.
It's a really strange error. Yesterday I thought I was honing in on it because I could successfully go from a working build to a crashing build by simply removing/adding a specific third party DLL. However, after a final successfull build last night, I shut down the computer. Today, I restarted it and opened the project, still without the offending DLL, and retested the build. And it's crashing. So now it looks like the DLL was not the problem.
are we allowed to tag the Admins? Judging by the facepalm reaction I guess that's a no. Sorry! I just don't see a normal user having the required knowledge of the engine to answer my particular question.
If it doesn't take too long, you could begin with deactivating some Scripts in different Builds and check if one of them is the source of your issue.
If the project itself isn't too big, you could create a copy of it or import its contents into a clean one, just to check if the issue still persists.
Also, it says [position out of bounds]?
Are you accidently moving something by an unexpected amount?
If you create a Build with just your Level0 Scene, with all Scripts deactivated, does it still crash?
Hi, thanks for trying to help! The problem is that I have already tried removing stuff, and have gotten successful builds doing so. That is where I left off last night. I removed a single DLL and was able to make a successfull build. The issue is, I have changed nothing in the project, yet today when I did another build, that build crashed.
So at this point I do not think the issue is a script, or a game object. I think the project may somehow be getting corrupted, which is why I'm particularly wondering what could possibly change between one day and the next within a Unity Project (when there are no user initiated changes). The build should be exactly the same, yet it is not.
And this is actually a crash from one of my users (I'm an Asset Store Publisher), so it's not local to my computer.
So, a User informed you about that, and you are able to reproduce it on your machine in a clean project?
Or did the user send you the seemingly corrupted project to try fix it?
If that's the case and you aren't able to reproduce in a clean project, then it is possibly an error on the consumers side.
You are sure that DLL didn't accidently get included into the new Build you made today? You already said that it doesn't, but better check twice.
I'd still try to activate/deactivate more scripts, or to just make a Build with Level0 without Scripts, or to try import your Asset into a new project and check if the issue persists, those things are (probably) done quite fast and will give you some important information if they do or do not crash
The worst case would be to ask support / open a ticket
- I am testing their (probably) corrupted project. I haven't seen the issue on any of my projects with my product, which is why I actually told the user I don't think this is an issue with my product. However, I then tested removing my product completely and did a build and it worked, so I was left scratching my head. However, now after going from not crashing/crashing between one day and the next, I'm back to believing it's not an issue with my product.
Still, I was trying to use the project as a learning experience for how to debug crash reports, however that ended up being a mostly dead end.
-
The DLL was not in the project at all on the Day 2 build when it started crashing again. I checked the Data/Managed folder on the build to make sure as well.
-
I can try deactivating/activating, but the fact that I have been able to get working builds with all of the supposedly corrupted scenes at one point or another indicates there is no actual problem in the scenes.
In any case, thanks for the help!
You shouldn't have to work on the consumers project in my opinion, instead he should give you a list of steps you need to take to reproduce the error.
Instead of removing your product from the consumers project, could you instead check if the user is even using it properly?
Also, is your product even able to cause a [position out of bounds] message? I'd take that one serious.
Maybe there's a corrupted art asset or prefab or something, which uses your product, but has an error in another of it's components
Thank you. As I said, this is more of a learning experience about how to debug crashes, it's not necessarily about helping the user fix their project. I only mentioned the user to say that the crash is not just local to my machine.
You are asbolutely right that it is not my responsibility to help the user as I am doing, especially since all evidence points to it not being an issue with my product.
Hi everyone, this code doesn't apply the rotation correctly, the desiredRotation is what I want it to be when its debugged to the console but it's not applied to the player correctly. So when the desiredRotation is 180 the player is rotated -126 degrees
They are just the benefactors of my own curiosity
It would still be great to not loose a customer to something that could eventually be fixed, he'll remember that before he buys another of your Assets, as well as he'll remember if you've been helpful
But I'd ask him to try replicate the bug in an empty project and give you the steps needed, pretty sure it's on their end
hey, how can i go about merging two arrays of samples from different audio clips into one single audio clip?
Very true. I've helped this customer a ton already, so I'm pretty sure they are loyal at this point :). Right now my work is about my own curiosity because I am absolutely perplexed by this bug.
Thank you for your time!
You're welcome! I'm out of ideas, sadly, I hope you'll succeed and find the cause of the problem!
Would be curious to hear the solution, if you find it 😄
At this point the only thing I can think to try is to keep upgrading the project to newer versions of Unity, in the hopes that the issue goes away or that there will be better error reports by Unity (because let's face it, level0 is corrupted does not provide much to go on).
Hey,
So I have an issue with Zenject/Extenject.
I have Player gameObject and it instantiate Character prefab by factory method and as a child of Player.
Also Player has GameObject Context component. And bind PlayerId in its installer.
In Character, injection happens for injecting PlayerId but unfortunately it throws an error about it can't recognise that.
So my question is, Does Zenject/Extenject support injection on child from GameObject Context or I have to inject it manually after instantiation ?
I have an issue with an event fiereing where unity complains about a missing object, but I don't understand why it's happening. I feel like it's something obv that I'm not seeing, hope y'all can spot it
Basically the error line 18 is called as soon as I spawn, but I don't get what's missing, the event? The error of line 84 is called when ReadyAuto is executed
mayb u want localRotation, I dont' really know
hey im trying to make a system where the longer you hold down a button the faster a projectile goes with the new unity input sytem but instead of the projectile fling when you release it flys once you press how may I fix this
try Input.GetButtonUp no?
does that work with controller?
0 idea, it's jut I don't know what context is so I don't know when it cancels
well its the left mouse on pc and back triggers on controllers
I mean that ctx class
can you show me the whole else if
because from this screenshot the else case never happens since it's an elseif with the same conditions
sorry
My man clean this code, just have an if with all them conditions and then have an if gunChosen != 6 inside it, with the logic for that and a return. then you place the normal logic. This is not the problem solution, but clean code is much easier to debug. I'm guessing you do not see the print statement right?
Also #🖱️┃input-system
Hello, I have an FPS character, as you can see in the hierarchy, the camera and the character model share the same parent, but inside the model I have ik constraints that allow me to move the body up and down with the camera flip up and down.
What I want to do is be able to have another camera inside the character's head so that even though the main camera stays in the same place, the other camera that is the child of the head moves with the body and I want that to be the one that renders, The problem is that when I add a new camera as the daughter of my character's head, the movement of the main one is cancelled, can someone please help me?
Hello! I'm having trouble wrapping my head around this particular problem. I'm sorry if this isn't the right channel. I'm also sorry if I'm not using the right terms.
The problem I have is that I need to drag a prefab into a script's public GameObject variable. But that prefab comes from an AssetBundle that is loaded in during runtime.
Is it possible for the script to remember the dragged in prefab?
If I'm correct I think you can't drag and drop a prefab directly from an AssetBundle into a public variable in the inspector because AssetBundles are loaded at runtime and the inspector doesn't have access to them at design time
That's what I thought too. I was just wondering if there was something about Unity I didn't know.
Thank you
Try this to see if it's what you're looking for ```public class MyScript : MonoBehaviour {
public GameObject myPrefab;
IEnumerator Start () {
AssetBundle myLoadedAssetBundle = null; // Load your AssetBundle here
yield return StartCoroutine(LoadMyAssetBundleCoroutine((loadedAssetBundle) => {
myLoadedAssetBundle = loadedAssetBundle;
}));
if (myLoadedAssetBundle != null) {
myPrefab = myLoadedAssetBundle.LoadAsset<GameObject>("PrefabName");
}
}
IEnumerator LoadMyAssetBundleCoroutine(System.Action<AssetBundle> result) {
// Load your AssetBundle here and then pass the loaded AssetBundle to 'result'
yield return null;
}
}
I think I have an idea with this. Thank you!
You are welcome
It keeps getting lost in general and might be a more advanced question anyway, I'd love some guidance/advice/reading materials related to this if anyone gets the chance: #archived-code-general message
Incremental SGs will be faster, but that speed difference will probably not be irrelevant unless you have written your SG in a really bad way/your project is huge.
Btw SGs don't just run during build, it runs in your IDE literally every key stroke you make, so it has the advantage over editor script that whatever code changes you make, SGs are instantly aware of them and regenerate new code without you having to tab in and out of IDE to Unity Editor.
If you don't need that capability, consider good old editor scripts.
For reference my project is around 80k LoC and it runs two SGs (which scan for attributes to generate code), even on my bad laptop it's instantaneous.
Do they both have the same frequencies and channels? If so, it's simply adding and clamping sample by sample.
that’s what i thought might work just didn’t have time to try. i’ll see if i can cook up something with OnAudioFilterRead
ArgumentException: Arial.ttf is no longer a valid built in font. Please use LegacyRuntime.ttf
This change appears to have happened in 2022.0.b3. Currently this is the workaround I'm working with. Is there a way to directly get whatever the default font is, regardless of version?
// Known bug: This may cause errors for some 2022 beta versions.
#if UNITY_2020_2_OR_NEWER
lbl.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
#else
lbl.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
#endif```
The Unity Documentation appears to be outdated for 2022 versions on this matter:
I see. I appreciate the response.
I’m just looking to make a mutable class that is a copy of an immutable class, but with every setter being public, and a method to copy the contents of the immutable class into the mutable one. Would you recommend a SG for this?
Yes, that's one of the good use cases of SG, especially if you are going to have many of these classes/edit them a lot.
i only plan on one for now, but I am working on learning to do these things properly.
the code for them just seems complicated, since all the examples are so dissimilar from what I’m trying to do.
General idea is, create your own ISyntaxReceiver and register it. In the receiver, collect all the information you need in order to generate all the code.
Then in ISourceGenerator.Execute, use the information collected by the receiver to generate the sources.
Can someone help me out? I upgraded from 2022 to 2023 and the following code stopped working.
Goal: I have no source texture. Just want to put output from custom shader to renderTexture.
Problem: It seems that the render texture is now just blank...
void Update()
{
backgroundMaterial.SetFloat("_UnscaledTime", Time.unscaledTime);
Graphics.Blit(null, renderTexture, backgroundMaterial);
}
This was working before. I'm hoping there's an alternative to get this working. I'm not suprised it stopped working as it didn't quite seem intended.
Any idea ?
from where do I offically get the latest unity headers
https://github.com/StephenHodgson/Native-Unity-API/tree/main
this link is somthing someone else uploaded
Its actually because I was using "quaternion" instead of "Quaternion" in the second line.
nooo, hahah
where do I get IUnityInterface.h and other headers ?
There are some specified in the native plugins docs https://docs.unity3d.com/Manual/NativePluginInterface.html
You should be able to find them in Unity\Editor\Data\PluginAPI
Hi , I want to attach a component to an object based on a string name
How can I do that ?
For-example I have a variable storing a random component's name
var componentName = "Transform";
I've tried Type.GetType but it returns null, even with UnityEngine.Transform as the name.
Hey people, I've got a question that's eating me for quite some time now and wanted your feedback.
What's the requirements to be a lead unity programmer?
I've been senior for quire some time and wanted to take a leap forwards but I'm questioning if I've got what it takes because... I'm not sure what it takes. I've got a lead in my team to ask, but wanted some more feedback. What's your experience?
hey. this is about Android builds. is it possible anymore to build for x86 architectures? Is see ARMv7 and ARM64 in the Player settings when IL2CPP is selected. but when I build and try to install to some android 6 (emulated) it says incompatible architecture (The APK failed to install. Error. INSTALL FAILED NO MATCHING ABIS) and after some Googling I figured it means the emulator's running as a x86 and the APK doesn't support that.
so, in short:
- is it even possible to run a Unity game inside a Android Studio's emulator?
- if so, how can I get either:
- Unity to build for x86 arc
- or Android Studio to emulate a x64 arc
isn't it too subjective though? should be very dependent on the size of the company/studio
Any code not in an assembly def seems to automatically have a reference to my asmdef, but not the other way around.
Is there any way to inverse this? I want to access things from the main assembly in my assembly def, and not be accessible from main
Hey. This coroutine freezes unity for 0.5 seconds, it is really annoying, can you give any advice what to do?
that's by design. your separate assemblies are to be treated like modules. the main assembly can use the modules, but the modules can't use the main assembly
a workaround is to put everything in a separate assembly, but that comes with some prices
Yes, but i want to inverse that design.
I want my tests to access my main assembly, but not the other way around.
not possible with the main assembly.
if you want the proj to be super organized, ideally your tests should be written for separate systems, and each system would have it's own assembly. by system I mean very different systems or modules (purchase/advertizement/IO etc.)
this will allow for a separate Test assembly for each system/module
Thats a very large change for us, not one i am interested in. Thanks for helping anyway!
you can use profiler's APIs to catch the timing of individual stuff. (https://docs.unity3d.com/ScriptReference/Profiling.Profiler.BeginSample.html) then use that to check individual lines, see which one's taking long.
Ok, thanks, I will
I am suspicious
that this one frreezes unity:
Can you give any idea how to fix?
I got it working by making a csc.rsp with a reference as such: -r:Library/ScriptAssemblies/Assembly-CSharp.dll
Yes. it is the part which causes freezing. what can I improve?
see the official docs, if that's supposed to be used in Unity they must provide some solution. else you can always just try and see if it's threadsafe and usable in a separate thread
ah, I didn't know that one.
What platform are you targeting?
Desktop
That first comment says something about it no
I checked with prfiler
and this code takes 500 ms
creating audio
var audioClip = AudioClip.Create(
"Speech",
SampleRate * 600, // Can speak 10mins audio as maximum
1,
SampleRate,
true,
(float[] audioChunk) =>
{
var chunkSize = audioChunk.Length;
var audioChunkBytes = new byte[chunkSize * 2];
var readBytes = audioDataStream.ReadData(audioChunkBytes);
if (isFirstAudioChunk && readBytes > 0)
{
var endTime = DateTime.Now;
var latency = endTime.Subtract(startTime).TotalMilliseconds;
newMessage = $"Speech synthesis succeeded!\nLatency: {latency} ms.";
isFirstAudioChunk = false;
}
for (int i = 0; i < chunkSize; ++i)
{
if (i < readBytes / 2)
{
audioChunk[i] = (short)(audioChunkBytes[i * 2 + 1] << 8 | audioChunkBytes[i * 2]) / 32768.0F;
}
else
{
audioChunk[i] = 0.0f;
}
}
if (readBytes == 0)
{
Thread.Sleep(200); // Leave some time for the audioSource to finish playback
audioSourceNeedStop = true;
}
});
Why not use native playback, since your comment says thats supported
Oh i have an idea to take off 200ms off of that
Comment that thread sleep?
I did that but
Still 300
remaining
This code is not mine. I copied it from Microsoft's text to speech sdk
but it has some problems
this has a 200ms thread sleep call? that's clearly meant for multithreading
Yeah
there are many stuff going on there
lock ing for syncrhonisation too
I have no idea why they needed to use that
So, I have to somehow create audioclip on another thread and wait for that
asyncly
I do not think that thing is thread-safe
but. can unity Job System help?
Ah shit
it now took around 1.6 seconds
I have to get rid of it somehow.
StartSpeakingTextAsync is already async.
this one?
As it says it is but. this code freezes unity
I commented Thread.Sleep but still
Nah, it is microsoft's sdk
ah
text to speech
this one. but very weird it has so many problems
Being the best available! - which does not always mean incredible, just better than whoever else is in the company or applying for a position. But if you want to lead a team of people then you had best have patience and ppl skillz
Because you are using .Result, which blocks the thread.
I tried that
that is not causing problem
But still. how can I make it work asyncly?
Maybe that can help too
Is Microsoft.CognitiveServices.Speech capable of good speech creation (sideways question)?