#archived-code-general
1 messages · Page 107 of 1
I can't remember exactly, but I got a problem when I used abstraction and solved it by using interface instead
Or vise versa
Can't really remember right now
Yes interfaces allow multiple inheritance
I think it was that
What problems would I face if I just made Tile a class and included it as an object in other types ?
depends on what your plans are.
hey guys!! I having some issue with a custom editor I made using the ui toolkit... so I am applying it on a scriptableObject script and when I click on one of the assets, I get this error:
The Error:
TypeLoadException: Could not load type 'EnumData.WildCardEvents' from assembly 'Assembly-CSharp'.
System.RuntimeTypeHandle.GetTypeByName (System.String typeName, System.Boolean throwOnError, System.Boolean ignoreCase, System.Boolean reflectionOnly, System.Threading.StackCrawlMark& stackMark, System.Boolean loadTypeFromPartialName) (at <890d6fe26e8c408ea64b353e791fafce>:0)
The Script:
public override VisualElement CreateInspectorGUI()
{
Initialise();
TreeSetup();
return root;
}
public void Initialise()
{
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
root = new VisualElement();
if(main_window_uxml == null || main_window_uss == null)
{
main_window_uxml =
AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
"Assets/--DEBUG_AND_TESTING/Wildcard data asset/WildcardUI.uxml");
main_window_uss = AssetDatabase.LoadAssetAtPath<StyleSheet>(
"Assets/--DEBUG_AND_TESTING/Wildcard data asset/WildcardUI.uss");
};
main_window_uxml.CloneTree(root);
_target = target as Wildcards_ScriptableObjects;
}
I have an enum element in the editor which is "WildCardEvents" and its coming from a separate class called EnumData... I never had this issue before... I just discovered it this morning😐😐
Some guidance on this would be appreciated
I'm trying to draw a line between two UI elements (for a skill tree), I just cant get the position of the both UI elements right. Tried alot of things from Google but none seems to be working, when the debug it says the position of all the UIs are same (its not), what can I be doing wrong?
what are you using to get the position of the UI elements
and what are you using to draw the line
I tried transform.position, rectTransform.position, rectTransform.rect.center and tried few other things things too like WorldToScreenSpace and stuff...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
This is my line renderer
did you try.. rectTransform.anchoredPosition? @lone umbra
not sure, giving it a try
yeah just did, not working, shows all positions as 0, 0, 0
for all elements
can you show the inspector of the elements you're trying to draw the line between?
oh they're under layoutgroups..
well not in its own script, alot of things are getting called, drawing line is the last thing I'm doing, but it all starts from the Start of Game Manager
can you temporarily test this
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
basically make the Start a coroutine
and make it wait a frame
see if it says the position is something other than 0
yeah I just tested it. you need to wait a frame before the position or size of elements inside of a layoutgroup is actually correct
hmm thats not working for me, maybe because my items are dynamic? The script is spawning both the LayoutGroups and the items in them, so maybe I have to wait, after doing that?
maybe
you might need to use the forcerebuildlayout thing
i'm testing it on my end actually, but i havent worked with line renderer in a while, and having trouble getting it to draw
haha yeah, layout groups are so bad, some quality assets on store has that forcebuild added to their scripts I've noticed before
is the problem that there's a one-frame delay before the layout group applies?
depends on what you mean by problem, haha
I think so, I've had alot of issues getting layoutgroups to act properly, specially if you are instantiating from code
it's kind of a quirk. it's weird
i'm actually getting that issue too
I've not had issues myself, hmm
it's different before I convert to world point
but after i convert, it's same
are you using a perspective or orthographic camera @lone umbra
perspective
wait a sec
are you using Camera.main.ScreenToWorldPoint
something about this, memxor. you need to add the z coordinate or something
Z=0 -> every screen point is the same world point
yeah that
you should check this out @heady iris
it's got a nice interactive diagram in it
ooh pretty diagram
yeah it's awesome
it just needs an ortho camera example
but do we even need World Point? in this case?
i believe yes because line renderer uses world coordinate, doesn it
Oh no, I made my own UI line renderer, it not Unity's Line Renderer
Ohhhhhhhh
that works in the UI?
oh wait, duh, of course it does
because you called it the UI Line Renderer
Unity's Line Renderer Component doesn't work in the UI system... So, let's create one that does...
Interior Mapping Shader - https://www.youtube.com/watch?v=dUjNoIxQXAA
Photo Real Assets - https://www.youtube.com/watch?v=Y538_YYhC1A
Fixing Grid Layouts - https://www.youtube.com/watch?v=CGsEJToeXmA
-----------------------------------------------...
it better work in the UI lmao
well, i'm out of ideas. it's wacky perspective camera stuff
can't get the line to draw properly on my end
I have a MonoBehavior script that subscribes to some actions of a ScriptableObject. Everything is fine, I press play, and when I stop the game view, I get an MissingReferenceException: The object of type 'MyScript' has been destroyed but you are still trying to access it. error.
Even though I don't destroy the game object anywhere. Is there a different object instance before I press play, and after the play mode ends?
PS: the error is shown after the event from the SO is fired again in the editor, meaning the script doesnt have access to the same isntance anymore i presume
@signal moon @lean sail I promised to create an example save system (#💻┃code-beginner message), here it is.
https://github.com/PillowCoding/UnityExamples-SaveSystem
The project contains a SaveManager singleton that keeps track of saving and loading. There is a sample scene with a manager that spawns random squares, and also a script that displays buttons, which calls both the singleton and manager to do stuff. Note I spawn the squares in 3d context and not in UI context so it might be weird. I'll change that later.
The idea is that SaveManager is informed of the stuff to save, and it will keep track of these references. When you tell it to save, it will collect all data to save, and save your Json at a location where it will persist (by default this is %appdata%\LocalLow\<company name>\SaveSystemExample (company name is probably DefaultCompany)). The same thing is done for loading.
Please note I whipped this up in the free time I had in the past 3-4 hours, so it is definitely able to be improved.
Feel free to fork, watch, whatever, this repo. Stars are always appreciated, especially since I aim to make that account more active in the future.
you also need to unsubscribe when you dont need it anymore, or the other object is destroy/removed/inactive
And also do a null check while calling your action
action?.Invoke();
thanks for the reply. I always want the script to be subscriber to the event. and I am doing a null check, so the event is subscribed to, but it is by a class instead of an instance somehow. as soon as it reaches anything GO related, it throws the error above
the error comes if I do anything in MapGenerator (AFTER the game has stopped; when the event is fired) related to the instance of the object (GetComponent, or gameObject.GetInstanceID() etc)
If I trigger a rebuild (by changing a script), everything works again, until I enter and exit play mode
it's like the instance that subscribed to the event doesn't exist anymore
and the subscription happens in the editor when the application is not running
why are you unsubscribing and subscribing again in the same place?
My guess to ensure that they don't subscribe twice
Unsubscribing when nothing exists will not do anything. If they already subscribed they now make sure that they don't subscribe twice
A better question would be; Why is this done in OnValidate and not OnEnable/OnDisable?
Can we bake navmesh based on colliders rather than renderers w/o the navmeshsurface component from the public repo?
It always use collider ?
@steady moat Uses renderers in 2021.3.10f1. Objects w/o renderers but colliders enabled are ignored
i have a Cube IN a Cube how would i find that Cube that is IN the cube in a script
like this
how would i acces the teleportPoint
and the script is in Shrine
isnt there a way to like do gameObject.Find
The same way you do it with anything else
It being a child of a parent object makes no difference
If you got a reference to the Shrine object, you can also do shrine.transform.GetChild(0)
Just remember this gets the first child, so if you have multiple things in there it's not guaranteed you get what you want
There are other ways of doing it, though
In the AI Navigation package, you can choose to use physics colliders. That option is on the NavMeshSurface
I dunno when that feature dropped (vs when they switched from the repo to a package in the registry)
yea i know
is there a way to get that child but with a name instead of an index
I guess something like this:
// You can use the methods `First`, `FirstOrDefault`, `Single`, `SingleOrDefault` and `Where` here.
// Note all these have different outcomes.
var teleportPoint = shring.transform.SingleOrDefault(x => x.gameObject.name == "TeleportPoint");
if (teleportPoint == null)
{
Debug.LogWarning("Teleport point was not found.");
}
I think you should set this up in advance
There are a lot of ways to do this
Assign these references in the inspector before the game even starts
what does that mean at the teleportpoint variable x =>
Hm, my version does not support this yet and I'm no longer seeing AI nav in the package manager. Likely it's built-in now?
Anyhow, repo it is as updating the client is a big nono. Thank you for confirming
Linq methods require a delegate as argument, and this is how you specify it
x would represent a child in this case
ah okay
It is experimental in versions of Unity before 2022
It's an advanced topic so I suggest you google delegates, Action type and Func type in c#
ok
The latter two are variants of a delegate
@heady iris I do have experimental packages enabled. Any idea what the package name is?
Look at the documentation for the older versions of the AI Navigation package
Experimental packages aren’t “enabled”; they don’t show up in the Unity Registry until you manually install them
Unless they've recently renamed something experimental packages
This was named experimental package for as long as they've allowed access to it
Until up to 2021
And sure this allowed unity to list them via the package manager
exactly, yes
because I have an SO that controls my map parameters, and when those change, I want the map to change in real time
but in the editor, not the actual app runtime
Hmmmm
I haven't worked a lot with editor specific stuff but I would assume there is a better way to do this
well, i've somehow figured out what happens, but unsure how to solve it. in the editor, there is one instance of my GO that subscribes to those events. when I press play, the same instance persists during application run, but is destroyed at the end of play, and OnDestroy gets called. Then as soon as the editor loads up again, onvalidate is called again and it resubscribes again, but the old subscription is still there for a GO that was destroyed. problem is if I try unsubscribing during OnDestroy it doesn't seem to want to unsubscribe for some reason
I'll check it out in a second, also to the questions in #💻┃code-beginner. no idea what singletons are and I didn't know json was serializable nor do I know how to do it xD
GameManageris a singleton here. Look for spots in it where_instanceandInstanceare used, because these are the parts that involve the singleton here. To put it simple, a singleton is an instance of something that is expected to only exist once. Basically the same asstatic, but the singleton has more functionality (such as existing as a gameobject).- You were using json with JSONUtility. This is very bad because it sucks really bad, and has a lot of limitations. Matter of fact, if I used it in the example project, I would get empty json back and it would not work. I use Newtonsoft instead, and this is actually added to your project by default with the latest LTS version. Perhaps they know JSONUtility sucks?
- You can view how I used my json in
SaveManager. Look forJsonConvertand everything around it.
I also used JContainer, which is something special. This is something from Newtonsoft and if you deserialize something without giving a proper class to deserialize in (or in my case I used object which does the same thing), it will deserialize it into something that inherits from JContainer.
Depending on the type, it will be either:
- JToken, for objects.
- JArray, for collections.
Since you would want to support both, and since both inherit directly from JContainer, I used JContainer here.
You also got JToken, which JContainer inherits from. You can also use this.
It's quite a big topic, so I suggest you google what most of those things are. It's very (very!) useful to know how this stuff works.
Feel free to ask questions regarding the repo
downloading 16f1 xD
You should be able to fork the repo and then open it in that version, but I never looked to deep if anything else is needed
is there a way to hook into the creation of MonoBehavior GO's at editor time? clearly an object is created then as well. start / awake only execute on playtime.
You can use [ExecuteAlways], or depending on what you want, Reset is a good callback that will be called when you add a component to a gameobject
my instantiated objects aren't showing up at runtime
they appear in the editor but they don't in the game view
oh my god nevermind i think i fixed it
the z axis was at like -311 i may be stupid
I see assembly files, was I supposed to use the package manager? xD
also almost everything in the GameManager is gibberish to me
No, this is just how I set up my project.
Editor folder is for editor specific stuff.
Runtime folder is for stuff that should exist at runtime
Samples folder contains a scene and scripts to make the sample work with the save manager
... There's no GameManager
If you mean SaveManager, then I'm not sure what's so scary about a file that's 121 lines, because that's very small
it's more the code in those 121 lines
Well, if something confuses you, you can ask me
I didn't comment that much because it's self explanatory really
public void Register<TSaveable>(TSaveable saveable)
where TSaveable : MonoBehaviour, ISaveable
{
...
}
This is a generic type parameter. the where part under it is related to it.
Basically I do not have a specific type to pass for saveable, because whatever must be saved must be both a MonoBehaviour and it must implement the ISaveable interface, By specifying a generic type parameter (which is the <TSaveable> part), I tell the method that it must somehow satisfy that, and you can then use that in the method (in my case I used it for the saveable parameter). You can also name it differently, but usually it is prefixed with T, and I considered this most informative).
saveable will also have all properties, fields and method that exist in MonoBehaviour. I don't really use it here except for saveable.Key which exists in ISaveable, and saveable.name which exists in MonoBehaviour.
This assures that whatever is added to the list in that method is valid. I could also just have object saveable as a parameter, but then there is no way to make sure that it is a MonoBehaviour, nor if it can save at all.
but then you can only save monobehaviors
You could remove that constraint, I don't think I have any specific reason as to why only those are allowed, other than displaying the name of the object
Then the only constrain is ISaveable and you could change the method definition to public void Register(ISaveable saveable), because that all fits inline now and a Generic type parameter is not required.
I guess I did it because I don't see a specific reason why non-Monobehaviour instances should be saveable, but it really does not matter
public class RecolorData
{
public Texture2D InputTexture;
public Material OutputMaterial;
public List<Color> Colors;
public void CreateMaterial()
{
//some code idk
}
}
if I have this simple class and I want to save instances of this class in JSON, how would I go about it with this system
I just gave an example, I don't know how far that system goes you know
As it is right now, it expects a manager that implements ISaveable, and this should fill your RecolorData class when ToSaveable is called.
You then use Register from the SaveManager and register this manager so the SaveManager knows it has stuff to save
it's just that I have no idea how to use it
Good luck figuring it out 😛
Saving data also has many ways of working, this is just something I came up with and whipped up real quick.
I mostly like it because the savemanager can keep track of what to save, and there's no need for events and all that
I only dislike the JContainer stuff, but oh well
NodeObjectTransform.GetComponent<MeshFilter>().mesh = Resources.Load<Mesh>("Cube.001");
makes the mesh filter a "None" and ofc makes the object invisible? this is how you change the mesh isnt it?
obviously your Resources.Load is failing
yeah
wasnt sure if the line was right or not with syntax
code is fine
I have a folder called 'Resources' with the mesh but not actually sure if that is how you set it up
screenshot the folder
looks ok, screenshot the inspector for Cube.001
What kind of file is Cube.001?
fbx
Unity treats 3D files as gameobjects
not a Mesh then
So you have to load it as a GO and get its MeshFilter.mesh
ahh
thank you
I'm allowed to drag the "Cube.001" onto the mesh filter in the editor and it will change it then so how come it doesnt in the script
Not sure what you are asking, can you rephrase?
Like what is your script
oops sorry, with the mesh I showed you, I can put that mesh on a mesh filter with no problems
its just that the script doesnt change it
What is your script though
for loading the asset?
public void GrabResource()
{
ResourceAmount-=1;
if(ResourceAmount <= 0)
{
NodeObjectTransform.GetComponent<MeshFilter>().mesh = Resources.Load<Mesh>("Cube.001");
}
Debug.Log($"ResourceAmount: {ResourceAmount} Node: {NodeObjectTransform.name}");
}
it was this
look at your code
you are saying Cube.001 is a Mesh so load it. But Cube.001 is not a mesh it is a GameObject
Again, you need to Resources.Load the FBX as a GameObject
Then access the MeshFilter.mesh of that loaded GameObject
isnt the cube different from the actual fbx
Yeah you actually need to access its children if im not mistaken
so me saying ""Cube.001"" it cant see that?
cuz the inspector of that obj says its mesh
Load BrokenStone or whatever the root object is called
it doesnt look like a stone i know xdd
can you say "BrokenStoneResource/Cube.001"
ah nvm it worked anyway thanks
"BrokenStoneResource/Cube.001
would that work too or no
Hmm probably not
and i thought i couldn't reference the stone thingy since it was a gameobject
so why did that work now lol
You can reference GameObjects just like any other objects/assets
Been coding for like 2h without being able to test...lets see how buggy this is lol
oh god
ya know (this is off topic) but i had a MySQL database and the trigger added a different record from a completely different database
how does that work lol
haha
3 bugs down
idk how many more to go 😭
5 bugs
please let it stop lol
whats the best way to remove multiple Items from a list?
issue Im finding is if I do
itemVEList.RemoveAt(0);
then the index of all the others I found is now off by1
Remove from reverse
Iterate through the list from the back with a reverse for loop
sweet thanks, was thinking maybe there was a better way 😄
maybe 8th time is the charm 😭
If you're just filtering the list and not performing additional work on it's items besides removing them, you might also consider a LINQ Where() - but it does return a new list, rather than updating the original in-place
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where
thanks
I'm having to remove some items to not break a sort and then adding bak in
9th time, Im sure this one is the charm
interesting problem
i come up with a two pointer algorithm
first you need a O(1) lookup table to check if the index is "dirty" (needed to be removed)
a pointer goes from forward and a pointer goes from backward
if forward pointer meets dirty element, then decrease the backward pointer until it meets a non dirty element (now the lookup table mentioned on above for O(1) checking), remove as swap "back"
O(n) algorithm but ofc you need O(n) space
I meant 10th time is the charm?
Congratulations. You've invented a linked list with some additional logic.
hello there, i am back and i am now trying the solution you provided, but i have a small issue with this, and that is, that when i exit the game (from the editor) i get these errors:
these come from this part of the code:
async void Receive()
{
if (socket == null || socket.Available < 0) return;
byte[] buffer = new byte[bufSize];
// this line right here -- the above check is apparently not working
await socket.ReceiveFromAsync(buffer, SocketFlags.None, epFrom);
Debug.Log("Received: " + Encoding.UTF8.GetString(buffer));
}
is there any way to check if it is disposed before accessing it? thank you very much!!
oh wait
i just noticed the < instead of <=
dang im an idiotXD
anyways it seems that correctly checking the Available property is enough
Gotta love when the entire day just feels like you are doing bug fixes
my teacher wants me to use the GUI c# for the ui "canvas" and it feels painful
xD
it feels like a crappy thing to use
you mean the immediate-mode stuff done in OnGUI?
Yo!
I'm trying to make a system where whenever I hover on a UI a panel shows up and follows my mouse until I unhover the UI. But there's a problem. I tried to make the panel follow the mouse by doing this but it goes off the screen.
is there an equivalent for the new input system for Input.GetAxisRaw() ?
solved this by adding the condition this != null in my callback
how can I use that to read the values from the byte array got from the ReceiveFrom method?
oh wait i think i got it
byte[] buffer = new byte[bufSize];
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
binWriter.Write(buffer);
BinaryReader binReader = new BinaryReader(binWriter.BaseStream);
byte packetType = binReader.ReadByte();
switch (packetType)
{
case 0:
// ... handle connection
string name = binReader.ReadString();
// ... etc
break;
case 1:
// ... handle message
string message = binReader.ReadString();
// ... etc
break;
// ... etc
}
can that be optimized? 🤔
Optimized or refactored? And is it an issue or are you simply wanting to prematurely optimize?
I'm trying to disable a field in the inspector for my component depending on whether or not a checkbox is checked. As an example, think disabling the "movement speed" slider if the "moves" checkbox is off. I can't find the attributes to let me connect to fields like this though
But I see some unity standard components have this behavior
Custom Editor
Ah so I can't just attributes
Thanks
did unity ever support python?
i just want to know if there is a less complex way of doing it, since i am grabbing the byte array and then writing it to a binary writer to then finally create the binary reader from the stream of the binary writer and then finally read the data
posting a video of the issue I had with my VR hand rotation.
Quaternion rotation = controller.rotation * Quaternion.Inverse(transform.rotation);
rotation.ToAngleAxis(out float rotationDegrees, out Vector3 rotationAxis);
Vector3 angularVelocity = Vector3.ClampMagnitude(_angularSync * rotationAxis * Mathf.Deg2Rad, Mathf.Pow(rotationDegrees * Mathf.Deg2Rad, _angularPower) / Time.fixedDeltaTime);
_rigidbody.angularVelocity = angularVelocity;
still no idea what's wrong with it
everything is fine but at 90 degrees on each axis the hand does a 360
OH
3 days later I found it
I attempted reversing the rotationDegrees if it has gone over 180 but I also needed to reverse the axis
if (rotationDegrees > 180)
{
rotationDegrees = 360 - rotationDegrees;
rotationAxis = -rotationAxis;
}
now it works perfectly
Could you use public MemoryStream (byte[] buffer); ?
Can it be optimized? Yeah, probably by not allocating new heap objects every time you read a new packet
You're eventually going to need to write an actual RPC system to handle calling functions over a network.
You can do it very easily with reflection.
Naughty has that if you want to use 3rd party
https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
hello, im struggling with ontriggerenter and ontriggerleave at the moment. I have included the script below but basically, i want to have abovePipe be set to false unless the player enters a specific collider and if they are in that collider, they can press r to rotate. Everything else in the script is working currently except for the fact that abovePipe is always true even when i first spawn in the scene and haven't entered the trigger. Is anyone able to help me figure out how to fix this?
public class rotate_script2 : MonoBehaviour
{
public int rotateDegrees;
public int rotateTarget1;
public int rotateTarget2;
public bool correctPosition = false;
public GameObject pipe;
public bool abovePipe = false;
void OnTriggerEnter (Collider coll)
{
abovePipe = true;
}
void OnTriggerLeave (Collider coll)
{
abovePipe = false;
}
void Update()
{
if (abovePipe == true)
{
if (Input.GetKeyDown(KeyCode.R))
{
Debug.Log("WOW");
transform.Rotate(0,rotateDegrees,0);
float yRotation = pipe.transform.eulerAngles.y;
//check whether the y angle of the game object's rotation vector is equal to the rotationTarget.
if(rotateTarget1 == yRotation)
{
correctPosition = true;
}
else
{
if(rotateTarget2 == yRotation)
{
correctPosition = true;
}
else
{
correctPosition = false;
}
}
}
}
}
}
(if this is the wrong channel, please direct me to the right place to ask this)
Did you put a debug log message in OnTriggerEnter? I'm guessing that it's being called and set constantly.
OnTriggerEnter will be called for any collision, so to set the flag you want you need to filter the collider you are colliding against to the type you want
yeah it's being called when the scene starts
how do i do that?
if you are able to explain that is, if u cant its ok
You need to set something on the other collider that the other game object is attached to that will indicate it's the type of collider you care about. You can use a tag or a layer.
Then when you get the OnTriggerEnter you check for that tag or layer before setting your flag
by doing this, does that mean i will need to duplicate the script and change the tag for every object I want to rotate?
right now i was planning on using the same script and attaching it to several objects
Ah so this script isn't attached to your player
no its on an object
It's attached to your objects, but accepts input.
You don't need to have multiple scripts then
The collider you are interested in is the one on your player.
So you need to add your player to a layer or add a tag to your player, then check for that.
(for context, this is what the box is like out of play mode
so add a tag to the player and check that where before the on trigger enter or after the on trigger enter?
after right?
It would be something like this in both enter and exit:
if (coll.gameObject.tag == "Player") {
abovePipe = true;
}
You have to check that you are entering a collision with the player on enter before setting the flag, then again check that you are exiting a collision with the player on exit before resetting the flag.
okay that fixed so that it isnt always true, but now its not turning true at all lmfao
void OnTriggerEnter (Collider coll)
{
if (coll.gameObject.tag == "Player")
{
abovePipe = true;
}
}
void OnTriggerLeave (Collider coll)
{
if (coll.gameObject.tag == "Player")
{
abovePipe = false;
}
}
Do you have the tag set on your player GameObject?
yea
Hello, how to detect that a button is being held down instead of a single tap in unity's new input system? ( Not the hold interaction)
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
float doesSpawn = Mathf.PerlinNoise(x + transform.position.x + chunkGen.seed, z + transform.position.z + chunkGen.seed);
float whatSpawns = Mathf.PerlinNoise(x + transform.position.x + (chunkGen.seed * 5), z + transform.position.z + (chunkGen.seed * 3));
whatSpawns = whatSpawns * chunkGen.trees.Length;
whatSpawns = Mathf.RoundToInt(whatSpawns);
GameObject current = Instantiate(chunkGen.trees[(int)whatSpawns], new Vector3(x * (128 / chunkGen.chunkResolution.x) + transform.position.x, y + transform.position.y, z * (128 / chunkGen.chunkResolution.y) + transform.position.z), Quaternion.identity);
current.transform.parent = transform;
i have made this code that generates trees with my terrain generator but it generates so many and i dont know why
all my values are correct
you're not checking if a tree should spawn or not, you're spawning them no matter what so it makes a grid of them
yes right now it makes a grid of them im just getting the basics down so i can build on it later
hello, how can i assign this null. for example to script's GameObject ,thx
wdym by "to script's GameObject"? that MyGarageCars class isn't a MonoBehaviour, is it?
yes it is monoBehaviour
OnTriggerLeave doesn't exist. It's OnTriggerExit
and is it normal to left it null, at end i want to save this garage list to Json file but it always empty
then you're doing it wrong. you should be using Instantiate or AddComponent to create instances of MonoBehaviours, you should not be calling its constructor
pretty sure you also can't serialize a monobehaviour to json
i have added a threshold and every single tree seems to stop spawning at the value 0.5
float doesSpawn = Mathf.PerlinNoise(x + transform.position.x + chunkGen.seed, z + transform.position.z + chunkGen.seed);
if(doesSpawn > chunkGen.treeThreshold)
{
float whatSpawns = Mathf.PerlinNoise(x + transform.position.x + (chunkGen.seed * 5), z + transform.position.z + (chunkGen.seed * 3));
whatSpawns = whatSpawns * chunkGen.trees.Length;
whatSpawns = Mathf.RoundToInt(whatSpawns);
GameObject current = Instantiate(chunkGen.trees[(int)whatSpawns], new Vector3(x * (128 / chunkGen.chunkResolution.x) + transform.position.x, y + transform.position.y, z * (128 / chunkGen.chunkResolution.y) + transform.position.z), Quaternion.identity);
current.transform.parent = transform;
}
thats the code it shouldent be happening
thank you ,I'll try other methods.😀 👍
Is it possible similarly how you can use [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] or [RuntimeInitializeOnLoadMethod] to reset values for statics, to have some registered method for SOs?
is there any way to make an awake method trigger before another awake method? Both of them are on the same object, and will always be
however, if the ordering of the components is the way to do it, it doesnt feel like a great way
another option is just having a component that triggers the awake methods (no longer awake methods) instead of letting unity do it
(also yes im aware of awake/start, but I need awake)
you can change the script execution order, but if one object is relying on another object it's better to do the stuff that relies on that other object in Start. use Awake to initialize its own fields and Start to access other objects
yeah, I have like 4 layers of it
so start/awake is not enough
(is it bad design? maybe xd)
server auth -> database retrieving data -> data manager (local data)
then the rest of the app is initialized on the Start method, retrieving the data from the DataManager
maybe you should use events instead
especially since I bet some of this stuff will take a non-trivial amount of time, and you wouldn't want to block the main thread
yeah probably
I am running into stack overflow issues, although my function does have an exit condition and is able to get very close to the exit before overflow occurs. Does Unity/C# have tail call optimization? Or does anyone have any general tips/ideas for avoiding stack overflow exceptions?
I don't believe there's tail call optimization, no.
:( grr
if it's a recursive call, can you cache the results?
dynamic programming time!
If you think you are going to reach stack overflow exception depth you might have to rethink your design
I just had the function wait a frame every 10 calls and that seems to have solved the issue, i guess its able to clear some stuff off the stack?
its mostly modifying gameobjects, seems difficult to cache results
anyone let me know if this is just going to cause further issues down the line 😅
ah true, also I guess it would just improve speed but probably not decrease the recursion depth
Alternatively
You could rewrite your recursion bit to use a while loop
And track the state manually
(make your own stack)
the function is quite large, im afraid tracking manually or trying to cache the results would be a massive undertaking
the stack does not "clear up"
a stack frame is created when you call a function and the frame is destroyed when you exit the function
that's it
why would waiting a frame stop the overflow from occuring then?
some other factor is causing it
ok, so lets say I know how many recursion calls im going to make, lets say 100. Is it possible for me to somehow split that up on the stack in segments?
or the first caller can never finish until all recursive calls are computed?
How do I run a function from different object when object x is ontriggerenter
Get the component from the object then call the method . . .
Maybe i dont really need to be using recursion?
lets say there are global variables totalRecursiveCalls and recursiveCount and a function called FunctionA(bool firstTime).
FunctionA(bool firstTime) doesnt return any values.
If FunctionA() is being run for the firstTime, it will calulate totalRecursiveCalls and set recursiveCount = 0
The last bit of FunctionA() is:
FunctionA(false);
}```
Can I achieve this functionality without recursion? It seems the first call of FunctionA() should not need to remain on the stack, as it is not waiting for any return values from the recursive calls... It seems like there must be a way to do this but I am too dense to see it
I don't really understand what you're describing there... or how pre-calculating the number of recursive calls you'd need to make will change anything, if you're just going to go ahead and recurse that many times anyway? 🤔
Just spitballing, but you might be able to move whatever logic and variables possible prior to/in between recursive calls to one or more separate methods, such that only the data needed to perform the recursive calls or return a value from it is present in the actual recursive method. In this manner, all of the supporting data would flick on and off the stack instead of hanging around and waiting for their respective recursive call's stack frame to pop... Not that I have any idea how that works with C# GC.
This only really seems like it might be a plausible solution if you're allocating massive amounts of memory per recursive call though - if the problem is more the amount of recursion, it's unlikely to change anything.
It still sounds like a greater rework may be the best solution
I mean yeah, I reckon I could technically run 1 function to determine the “totalRecursionCount” and then just run a for loop which would loop that many times and run the function each time, but this wouldn’t reduce the size on the stack either… correct?
Assuming you only store the state required to get from one call to the next outside of the function in question, I would think it would, to the same effect as breaking up the recursive function into smaller supporting functions - generally just clearing all of the stuff off the stack between calls which was just used to calculate arguments or return values.
But that may or may not make a real difference, depending on how much persistent state you actually need... I'm finding it really difficult to think hypothetically - it's been a while since I've used much theory 😅
If there's a different issue, none of the above would help. But generally, you could avoid recursive call stacks by simply using a loop. Else, I'm assuming you're simply using too much or have got some undefined behavior causing it to not properly terminate.
I am sure that it’s properly terminating, it’s just that when I have to run the function a lot of times it takes up a bunch of memory
On a side note, I still don't think there's any reason to precompute the number of calls necessary - whether in a loop or a recursive method, you'd presumably want it to just run until the problem is solved either way
Maybe show the exact error if you're allowed to.
And the code.
I mean I could show the code but it’s thousands of lines
If the exact error would help I can do that as well but I was trying to simplify the problem by speaking theoretically
The recursive issue couldn't have been a thousand lines, could it?
If stack overflow is occurring, you're either never ending or putting way too much on the call stack.
Yeah it’s the latter
Maybe figure out why it's happening rather than try to bandaid it.
I want to be able to reduce the size I’m putting on the stack by breaking it up but I’m still unsure if that’s possible
Just to be clear, it won't matter if it's infinite or near infinite. I pray your stack eventually ends.
No it’s about 100 calls
Are those 100 calls all recursive? like call 1 cannot execute until call 100 does?
No
That’s what I was trying to explain here… but I I think I did a bad job
The very last thing call 1 does is call itself, but it doesn’t need any return values from that call
Ends up overflowing around 87 calls
oh well that's still a recursive call lol
if you do it that way then call 1 will still be on the stack until call 2 finishes which will still be on until call 3 finishes etc
What about this tho?
why not just call the thing 100 times?
Yeah that’s what I was thinking
that way only one call will be on the stack at any given time
Hello, I'm trying to make a game where The player can move backward, forward, and jump in a 2D Space with an Orthographic camera.
I tried A lot of ways to make it work, but I always get to a dead-end, and I need help.
Yeah I think I’m just struggling with it conceptually but I should be able to implement that
It'd just be a loop, which has been mentioned multiple times now.
So that is or is not a solution? Lol 🤯
Before tail recursion was a thing, looping was the solution to avoiding stack overflow.
Ok cool
implementing it depends on whether or not your stopping condition is dynamic
No the stopping condition is determined during the first call
okay then shouldn't be too bad
Well it will be a little weird because I use IEnumerators to (in some circumstances) add pauses between calls, so the for loop will have to be in an IEnumerator but that shouldn’t be a problem…
I’m having problem with my movement whenever the player rotates they start moving all across the place
don't crosspost. try providing more details in #💻┃code-beginner where the question belongs
Sorry
This isn't a big deal as I don't require it, but is there anyway to initialize what the default for something like this is?
Material activeMat = Resources.Load<Material>("Assets/Materials/BatteryActiveMat.mat");
I am aware that I can just initialize it in awake or start, and that I can simply drag in the materials I want and make a prefab, but this would just be a bit nicer imo.
well for one, Resources.Load won't work with that argument. the material would need to be inside of a folder named Resources which would be in the Assets folder, and you'd only include the path to the file omitting the base Resources/ folder and the extension.
but also no, you won't be able to assign it in a field initializer. you could serialize the field and assign it using Resources.Load in Reset() which would get the material and assign it to your field whenever you reset the component or add it to an object using the editor
ok, thank you
hi everyone. I need help with a problem which solution i can't figure out, I have two gameobjects with the same script, that script has an if statement that should execute it's else if statement depending on the value of a public boolean, so when the public boolean is checked, the if statement executes and does thing 1, and when the public boolean is unchecked, the else if executes and does thing 2, and I want gameobject 1 to do thing 1 and gameobject 2 to do thing 2, but sometimes the if statement executes when it does not have to, and sometimes it works fine, and the same with the else if statement, how do i fix this?
that is really hard to understand, dont obfuscate your logic when asking how to solve it. Just ask the proper question and/or show code
plus this seems more like a beginner question
this is also a #💻┃code-beginner but yes u do need the players location to have something look at the player..
@tired ivy dont dm me your question. I said to put it in #💻┃code-beginner for a reason
mb
is it normal when you create new c# script and in visual studio it resets to miscellaneous files
That would imply that you're ide is not configured
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
When I run these event handlers it only prints the "nodeIndex" on every second click, so the first click it prints "someth clicked" empty, then it will print whatever was clicked, if i click something else it will say the last thing clicked and if i click again then it will say what i clicked then?
private void NodeObject_TownHallClicked(object sender, EventArgs e)
{
Debug.Log("Hall Clicked: " + ResourceNodeIndex);
}
private void NodeObject_ToolShedClicked(object sender, EventArgs e)
{
Debug.Log("Shed Clicked: " + ResourceNodeIndex);
}
private void NodeObject_StoneResourceClicked(object sender, EventArgs e)
{
Debug.Log("Rock Clicked: " + ResourceNodeIndex);
}
I feel like I've done something stupid lmao
(fixed for now)
Hi guys when i try to export my project to android studio "libil2cpp.so" file is going missing in the jniLibs folder, as a result the build is crashing anyone faced similar issue , and does any one have any solution for this?
The build is crashing or does unity fail to build the app?
build is crashing
Im not 100% sure but is it even supposed to be included in the build?
No libil2cpp.so in the jinLibs
Do you have the C++ workload installed in visual studio workloads? I know it's needed for normal IL2CPP builds, but perhaps it's also required for export to android studio
i think no, let me check that, but in the earlier version of unity i had no issues, when i upgraded the project to 2020.3.43f1 this issue started
Also, what do you have the scripting backend set to in unity?
its il2cpp
I'm a little confused, what do you mean by 'export my project to Android studio'? As far as I am aware there is no such functionality
Exported the unity project and opened it in android studio
As I said, there is no such functionality to do that in Unity
There is, you can export you projects in android platform
and you can open them in android studio
show me
There is actually. Unity converts the project into a structure that android studio uses.
I've never used it myself, but it has its uses.
yes
I stand corrected, you learn something every day. I've never even noticed that option, I just build the apk and load that into AS
Hey, I can see that Easy Save 3 is on sale. Has anyone used it and can say if its worth it? Because from the documentation it just does not seem like its worth the price to me. Does it simply work like it can dump entire gameobjects/prefabs into a file?
It seems like it can serialize the entire GameObject/prefab, yes. Nothing you can't accomplish yourself, but it could be a solid solution that would save you time from implementing one yourself. Wether to buy it or not is entirely up to you.🤷♂️
@restive dirge It looks like in 2020 Unity does not create the il2cpp.so. It outputs a complete source project so you have to build the .so yourself
yeah
am on research doing so , currently dont know to build .so will try to find it out
what I would suggest you do is build an apk then look in the build logs to see what commands unity uses to build the il2cpp project
np. it is odd behaviour, i dont know why they changed this from 2019
hello ! Is the "instantiate" command also duplicates the 2D texture of the object and preserves its UV coordinates so that when I setpixel on the original object, the texture of the new one does not change?
I think you will find that although the Material is instanced the underlying Texture is not
References to assets are not duplicated and materials/textures are assets. The material would get duplicated if you access it implicitly, but the texture wouldn't.
Hello, how do you people fetch the current time and cache for hourly rewards and what not? I do not want to record the local time as it could be tampered with, so are there any APIs that you use the record the current timestamp? I was previously using a plugin which used http://worldclockapi.com/api/json/est/now but it no longer seems to be working. Any ideas?
Above can still be tampered with
You need some form of user authentication + a database that tracks when they last requested their rewards
Hi, I'd like to ask is there any way to increase a rigidbody moving speed without affecting its destination? I'm shooting projectiles to input mouse position using projectile motion, everything is nice, the angle, the curve,... but not the speed, I want to move faster or slower.
physical projectiles fall at fixed rate defined by gravity, if you change velocity you overshoot undershoot the only way to compensate for that while using physics is to adjust the aim
I guess I need to find other methods to shoot projectile to achieve it. Thanks 😄
you could write some formula to compensate for speed adjustments, but i dont know how complex that would be
Changing gravity is another option.
true
where can i find unity documentation for the new input system? specifically for InputSystem.SetDeviceUsage?
I make games that use a console, like Stardew Valley or Minecraft servers, but Unity doesn't bring up the C# console when I run my project, so how can I get it to do so? This question was asked earlier in another channel, but I switched channels, so I apologize for that!
try checking the pins in #🖱️┃input-system
what do you even mean by 'C# Console'?
Hi, first of all thanks for your interest in my question, by C# console I was referring to the exe file that comes out at build time after creating a project in Visual Studio or Rider with Console Project in the .Net Core or .Net Framework tab.
that is not a 'C# Console', that is just a standard Windows command line window
Okay, so how do I bring up the standard Windows command line window?
you don't. Unity builds a Windows program, they dont have a CLI
I can't quite understand this, does it mean there is no way?
Windows programs have windows, command line programs have CLI's, the 2 are not interchangeable
is there a way? Yes, but you need a deep understandig of the Windows OS and the Win32 API
Is there another way to approach it, like adding a console project to your Unity solution, or creating a console project separate from your Unity project so that the two interact with each other?
you could certainly do that but, again, you would need an understanding of the Win32APi to achieve it
Thank you, that was helpful enough, I appreciate your time!
I know this may sound stupid but does anyone know how to round double to the nearest whole number?
Might be a weird workaround:
Mathf.RoundToInt((float) myVariable)
This converts it to a float first, then rounds it
Tyvm, I saw a similar solution on google but I didn't understand what it did so I didn't wanna risk trying it lmao
google is an amazing tool 'c# round double to int' first answer
I did look on google, however it was all mumbo jumbo to me, I'm very new to unity, so I'm used to basic C#
this is basic c#
Mathf wasn't in what I learned but alr
Math still exists, and is more suited to what you asked, doubles
How would I access it, because when I tried to use math functions it says math is not defined
Same way you access anything else
the first solution doesn't use Math it uses Convert
heyoo, so I'm in the process of creating some stores in my game and want to be able to edit the inventories easily, would this be achievable as a JSON in the resources folder?
why the resources folder
and are these needing to be editable at edit time, or runtime?
edit time, never ever run time
JSON works (as TextAssets)
Or you can use ScriptableObjects
i guess any folder in assets would work...
rightt, ta. I've had a look at SO's in the past but JSON is something I deal with regularly anyway and I'm confident with that so will go down that route. This just needs to work 
As TextAsset makes it easy
you just do like:
public TextAsset MyJsonFile; // assign in inspector
void Example() {
string json = MyJsonFile.text;
MyClass data = JsonUtility.FromJson<MyClass>(json);
}```
thanking thee 🙂
oh neat, I wasn't aware of TextAsset
component that reads a text prompt, crams it into an LLM, and then dynamically loads the resulting code at runtime

If I am changing the speed of time, how do I get the correct time between frames?
deltaTime += (Time.deltaTime - deltaTime) * 0.1f;
I am using this but I feel it is wrong
what do you mean speed of time? you changed the timescale?
Yeh
I am trying to create and FPS thing but I am pretty sure it's not working when I speed things up
My logic might be wrong somewhere else
oh it is
when you say correct time
do you mean the deltaTime at timescale 1?
or the deltaTime after you changed the time scale
at timescale 1
Oh smart, thank you
Good job I noticed this because part of my module was comparing the FPS with dots on and off
And the FPS was lower than it was supposed to be because it scaled by time
So basically at 2 times speed it was halving the fps 😅
I was also averaging my FPS faster so from 0.5 seconds to every 0.055 seconds o-o which was costly
It's insane how much of a performance boost it gives
might seem like a dumb question but is there any reason why you would use the builtin methods for moving an object like MoveTowards or Lerp if you have a tweening library? or will a tweening library cover all your needs for moving something?'
like does it make sense for an AI like a boss to use tweening to move around?
Not really.
You usually use constant speed.
what if i trained bot for a year
will it be the hardest bot?
Or some modification of speed that does not follow tweening logic.
No. The efficient of learning reduce with time.
depends on the training
oh
In almost every form of learning possible
how can i train it shooting like player?
oh
alright
thanks
btw if you dont mind
can you go to #🖱️┃input-system and answer me please?
I need some help with the particle system. I want to create some 3D particles but directly from C#. I am trying to copy the mesh from a primitive to the mesh the particles are supposed to use, but it doesn't seem to be working. The code is quite large so I will post it in a thread
yo this is my code, https://gdl.space/solaqocahi.cs
I'm having an issue where the Packet that runs MatchCheck (which is the one defined as startPacket in the method) doesn't end up being included in the matchedPackets list, when it reaches the LaunchNewGroup() method
how do i write this to work because these lines are obsolete
UnityWebRequestMultimedia.GetMovieTexture(path))
and
DownloadHandlerMovieTexture.GetContent(unityWebRequest);
it suggests using csharp VideoPlayer instead but im not sure how to do this
IEnumerable LoadVideo(string path)
{
using (UnityWebRequest unityWebRequest = UnityWebRequestMultimedia.GetMovieTexture(path))
{
yield return unityWebRequest.SendWebRequest();
if (unityWebRequest.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(unityWebRequest.error);
}
else
{
var unityWebRequestVideo = DownloadHandlerMovieTexture.GetContent(unityWebRequest);
videoPlayer.clip = unityWebRequestVideo;
}
}
}
i am trying to load a video from the file explorer
does anyone know a way to do this
Any tips on PropertyDrawer formatting? For the STruct I've turned into a Property Drawer when I have an array of the struct to show in Unity Editor properties of that struct overlap with other elements of the array
wow this is actually stupid
VS2019 has no lag when using it
VS2022 now has like 200ms lag when using it 😭
I have no issue with VS2022
I haven't until the last week
Is there a way to make Unity reload script assemblies either ONLY when I start the game, or in the background when I save in VS?
Go to project settings > editor > play mode settings > turn on play mode options, then make sure domain reload is turned off (which it will be by default)
like such?
yep
that helps a lot...however I want the opposite of that lmao
where it only refreshes when i click play, or just refreshes in background when saving in VS
that should make it so when you change and save code in VS...that it doesn't reload
"reload script assemblies" when you tab back?
I use CTRL-R to then refresh
You can make code to call the function AssetDatabase.Refresh whenever you want otherwise.
big sad
it still makes me wait for reload script assemblies with that setting set like that
ooh, just found this from 2 days ago
lets hope it fixes it
"Visual Studio: Tools -> Options -> Tools for Unity -> Refresh Unity's AssetDatabase on save: False"
still doesn't do crap
darn
It works from my side. Enabling and disabling the settings behave as intended.
Im guessing you aren't in the 2022 version
True, I am in 2021
But, the user did not report if it was working in 2021, so I would not think it is actually an issue due to version.
I should have left my project in 2021 😦
hmm it's true
reload assemblies seems to occur no matter what
I can't get it to stop on 2022 either
"Visual Studio: Tools -> Options -> Tools for Unity -> Refresh Unity's AssetDatabase on save: False"
does this setting do anything for you?
doesn't seem to do anything for me
I'm using VS Code, so I can't use this
F
You can also test it in 2021, and if it actually does work in 2021 and not in 2022 it would be easy to make a bug report.
https://www.reddit.com/r/Unity3D/comments/zbnx64/i_finally_fixed_my_ultra_slow_assembly_reload_time/ still didn't fix the issue
however my reload times are much lower now 😄
Hey, how can I modify terrain height from script, to align with some planes I have? I am generating a path along a spline, and i'd like to align the terrain to it somehow.
Is there a way a could stretch only the edges of a sprite?
In other words the middle would keep 1:1 aspect ratio while the edges could be stretch by a percentage.
What causes a referenced item to disappear in the script in the inspector during play mode. The item is an animator, its a component of the item the script is on, its [SerializeField] private Animator animator; I drag it in the script and when I push play to test is disappears and I get a reference null error. I tried changing it to public Animator animator, same thing. I tried Animator animator and then got it in awake. etc. etc. I have also deleted the item, and started over.
something is destroying your Animator
Are you overwriting it in start or awake
With a GetComponent or something
no, there is no start or awake, just update and the variables
Then is the animator being destroyed?
destroyed in the inspector, no, just loosed the refrence
{
Debug.Log($"{(influenceChange[kvp] < 0 ? "" : "+")}{influenceChange[kvp]} {kvp.faction} Influence in {kvp.country}");
Game.current.gameState.influence[kvp.country][kvp.faction] += influenceChange[kvp];
kvp.country.InfluenceChangeEvent?.Invoke(kvp.faction, influenceChange[kvp]);
}
This foreach through a tuple-keyed dictionary is causing a "at least one item must implement IComparable" exception. The options as I see them are: 1) add IComparable to either Faction or Country (for no other purpose than to resolve the error), 2) create a struct holding faction and country and replace the tuple-as-key 3) rewrite the foreach so that no IComparable is needed. Which of those options are the best approach and is there another way to solve this issue?
normally when i get this, its because i forgot to call it in Awake, so I reconfigured the script and it still does it.
Show the script
You mean in the Hierarchy
public class WeaponWheelController : MonoBehaviour
{
[SerializeField] private Animator animator;
public Image selectedItem;
public Sprite noImage;
public static int weaponID;
private bool weaponWheelSelected = false;
void Update()
{
if(Input.GetKeyDown(KeyCode.Tab))
{
weaponWheelSelected = !weaponWheelSelected;
}
if(weaponWheelSelected)
{
animator.SetBool("OpenWeaponWheel", true);
}
else
{
animator.SetBool("OpenWeaponWheel", false);
}
switch (weaponID)
{
case 0: //Nothing
selectedItem.sprite = noImage;
break;
}
switch (weaponID)
{
case 1: //Knife
selectedItem.sprite = noImage;
break;
}
switch (weaponID)
{
case 2: //bow
selectedItem.sprite = noImage;
break;
}
switch (weaponID)
{
case 3: //water
selectedItem.sprite = noImage;
break;
}
switch (weaponID)
{
case 4: //food
selectedItem.sprite = noImage;
break;
}
switch (weaponID)
{
case 5: //inventory
selectedItem.sprite = noImage;
break;
}
}
}
And you only have one of this script in the scene?
yes, there is another animator on a child of this, but it has its own script
its done in the same way, and does not disappear
hey so i have this code where i set a refrence, but in the inspector it tells me type mismatch, altho the type IS a match
Really not sure then. Sorry
damn it. lol, im stumped too
i do appreciate your time though.
why does it give me type mismatch?
What's the animator you're dragging in
one is weapon wheel and the other is the weapon wheel button, i made sure i did not have the same one in both
Not sure, have you tried removing it and reassigning?
no
I deleted the game object and rebuilt it, added the animator and the script etc etc.
Try making a new scene with just that script and a random animator dragged in
Isolate it
will, do. Thanks again
Are you changing Ball to a reference to a scene object during play?
Doing that and exiting playmode will result in a mismatch
Hey, so I tried asking ChatGPT to make code stretch the edges of sprite, while keeping the center unchanged.
After a few extra instructions it came up with this.
private void V1() {
// Define the slice positions (normalized values ranging from 0 to 1)
var sliceBorders = new Vector4(0.1f, 0.1f, 0.9f, 0.9f);
// Calculate the slice sizes based on the sprite's dimensions
var spriteSize = new Vector2(_spriteToSlice.texture.width, _spriteToSlice.texture.height);
var sliceSizes = new Vector2(spriteSize.x * (sliceBorders.z - sliceBorders.x),
spriteSize.y * (sliceBorders.w - sliceBorders.y));
// Calculate the slice offsets based on the sprite's dimensions
var sliceOffsets = new Vector2(spriteSize.x * sliceBorders.x, spriteSize.y * sliceBorders.y);
// Calculate the scaled edge sizes
var scaledEdgeSizes = sliceSizes * edgeScaleFactor;
// Calculate the final slice sizes by combining the scaled edge sizes and original center sizes
var finalSliceSizes = new Vector2(scaledEdgeSizes.x + sliceSizes.x * (1 - edgeScaleFactor),
scaledEdgeSizes.y + sliceSizes.y * (1 - edgeScaleFactor));
// Create the sliced sprite
var slicedSprite = Sprite.Create(_spriteToSlice.texture, new Rect(sliceOffsets, finalSliceSizes),
new Vector2(0.5f, 0.5f), _spriteToSlice.pixelsPerUnit);
// Assign the sliced sprite to the SpriteRenderer component
GetComponent<SpriteRenderer>().sprite = slicedSprite;
}
Only thing is, it only seems to remove the edges, not add them back. The first few lines seems ok, thoughts on what's wrong or is there just a limitation when it comes to making a sprite from multiple?
Thanks!
its durting play and the ball exists, its a missmatch, not a missing object
this is outside of playmode
Ok what I said is still true
What are you expecting it to show? That object is already destroyed
which part exactly
So what is the problem?
The reference becoming invalid when you change the scene/exit play mode?
How's it going
i had to take take care of some other stuff at work. Ill get it here in a bit or later tonight.
my question is why does it show it as mismatch
Probably because its an asset in the disk and it cant store a reference to an object in the scene.
Does the asset say Mismatch when youre playing and not even changing scenes?
i dont change scenes, like i sayd the ball is in the scene and at that point it says mismatch
when the ball is not in the scene it just says missing
@prime sinew it did it in another scene.
It removed it?
yep,
I was specifically asking about play mode. What does it say in play mode
yes, playmode
That's so weird. I'm stumped too
@prime sinew guess its time to start fresh.
It probably just looks messed up because a SO isnt supposed to reference a scene obj.
Restart unity. Turn it off and on haha
If you do figure it out, do share if you remember
I'm out of ideas
will do.
ok
How do I add a comment/summary to a Monobehavior to show in the inspector
do u mean a tooltip?
Hmm, I want it to show at the top of the component, not on hover
You can probably use [TextArea] then
You need to do a custom editor.
Maybe there is solution like Odin that implements it.
Sorta
[TextArea], [ToolTip], [Header] I think are all of them
Naughtyattributes has some more flavor text boxes
Oooh
That might me what I'm looking for
Docs is loading super slow for me...
Or just bad internet
Eh, nvm it's not necessary atm
@prime sinew I went back in and deleted the animation controller and rebuilt it. I then created a new script and copied and pasted the old one in. I changed it to Animator anim; and called it in awake and.......yea, its working. thanks again for at least trying to help. have a great day
Hi! which method to use to save the data when exiting the game on the Android platform in the format newtonsoft.json?
public class Enemy : MonoBehaviour
{
[SerializeField] private int moneyPerEnemy = 10;
[SerializeField] private TextMeshProUGUI moneyText;
private int totalMoney;
void Update()
{
UpdateMoneyText();
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Bullet"))
{
AddMoney(moneyPerEnemy);
}
}
private void AddMoney(int amount)
{
totalMoney += amount;
UpdateMoneyText();
Debug.Log("Added " + amount + " to player's money.");
}
private void UpdateMoneyText()
{
moneyText.text = totalMoney.ToString();
}
}
hello guys, in this script i have a problem that even if the enemy collide with the bullet the TextMeshPro not changing why?
Does the Added money is being print ?
Does your code throw an exception ?
Is the TextMeshProUGUI the one that you are seeing ?
Is the Enemy enabled ?
Is moneyPerEnemy more that 0 ?
And, you should not make your enemy control your UI.
If you have multiple enemies, you gonna be screw.
1.yes
2.idk
3.yes
4.yes
5.yes
Do you have multiple enemy ?
yes
Then it is obvious why it is not working
You have at least one enemy that set the value to 0 because it has not been incremented
An easy fix would be to make the variable static BUT, and I insist, you should restructure your code.
A player has money
An enemy contact a bullet that is own by a player
The player that owns the bullet earn money (the amount the enemy is valued at)
When the player gains money, it notifies the UI to be updated.
If your game has no notion of Player, you could replace Player by GameManager.
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Weapon currentweapon;
void Start()
{
currentweapon = new Weapon1();
currentweapon.Attack();
}
}
public class Weapon
{
}
public class Weapon1 : Weapon
{
public void Attack()
{
}
}
public class Weapon2 : Weapon
{
public void Attack()
{
}
}
public class Weapon2 : Weapon
{
public void Attack()
{
}
}```
^ can someone help implement something like this? i think the code is pretty self explanatory for what i'm trying to create here but if you want a better explanation let me know
in the way that it is right now the currentweapon.Attack() is giving an error, i know that's the wrong way of writing it i'm trying to figure out what'd be the best way of writing that
In C# you have to mark overridden methods explicitly with override and the parent method has to be either abstract or virtual
also if you want an abstract method in a class, the class itself must be abstract
Umm.
You probably want the base class to implement the Attack method too.
And then add the Override keyword to the child class implementations.
The base class can be just an abstract declaration.
Also when sharing, please don't just say "an error". It is much better to share the actual error
you also have 2 Weapon2 classes
i figured
the code's there only to give an idea of what i was trying to make, i didn't necessarily want it to be "fixed"
thanks for the answers tho appreciate it
Sure but without saying what the error is it could be almost anything
so we won't be able to give good answers
if(hit.transform.gameObject.GetComponent<UnitBehaviour>() != null) unitType = SelectionType.UNITS;
Instead of checking whether the gameobject has UnitBehaviour attached to it, I want to see if the gameobject has any subtype of UnitBehaviour on it. (ie MinerBehaviour or BuilderBehaviour as they both inherit from UnitBehaviour)
this code will work just fine for that
however if you want to check that, you should use TryGetComponent rather than GetComponent, for simpler code:
if (hit.transform.TryGetComponent(out UnitBehaviour _)) {
unitType = SelectionType.UNITS:
}```
why do i need the out UnitBehaviour _ section. also unless im being silly my original code doesnt seem to work. will double check that everything else is okay tho
It's just a required argument - and also specifies the component type to search for, without using the generic type parameter
to tell it which type to get
It is inferring the generic type argument from there - and it's also spitting the component out there but you're ignoring it hence the discard variable name _
if you want to use the variable, give it a name:
if (hit.transform.TryGetComponent(out UnitBehaviour ub)) {
ub.DoSomething();
}```
in this case since you dont need the arguement at all, is it not better to just use TryGetComponent<UnitBehaviour>() ?
no because that will be a compile error
since that's not what the method signature is

Though apparently you can pass null?
TryGetComponent<UnitBehaviour>(null);
🤔
Oh no that doesn't work
it needs an out param
i see
The docs mention null as a possible argument, but don't elaborate on that 😕
I recommend this formulation
alright well im currently in extreme pain becuase of how poorly my code is laid out and i cant be bothered to go through it all and fix it so ill try this again tomorrow, thanks for the help @leaden ice and @wide terrace
I was mostly just here to muddy the waters 👍
Good luck
nah you were helpful too 👍
Hi this is a script from a Meteos clone im making. https://gdl.space/solaqocahi.cs
I'm having an issue where the Packet that runs MatchCheck (which is the one defined as startPacket in the method) doesn't end up being included in the matchedPackets list, when it reaches the LaunchNewGroup() method
If there is an nvidia gpu as the gpu, does it make sense to do some operations with the cuda toolkit and optimize it?
Well... that is what compute shaders are for. Yes.
Cuda would work only on nvidia. But compute shaders "hide" that platform specificity.
As far as I know, with the cuda toolkit, it was making to run mathematical operations and functions in c# and other languages with gpu processing power.
Cuda is build on C and is proprietary to Nvidia.
OpenCL is a bit better but its not up to par feature-vise.
But you are in a unity discord. So I assume you want compute shaders. They can do almost anything raw cuda can would be my guess. (probably a bit slower tho?) not sure. Have not dabbled much.
I had heard in an article that the GPU can perform faster operations thanks to its more core structure, so I asked this question.
GPUs use SIMD
at an insane level
your CPU has SIMD capabilities that most developers don't take advantage of
If I learn to use multi-threading with the System.Threading library, is the performance worth it?
If you have to ask, then probably not
hmm
If you don't do it right, you'll make it slower than single threaded.
Most tasks don't require a whole ass dedicated core
why does my image color turn transparent when changing color It should just be orange
public Color orange;
healtBar.color = orange;```
because you haven't assigned a value to orange
so it's defaulting to transparent I guess
I changed the colar to orange in the inspector
nvm fixed it
Hey, is there maybe anyone that can help me?
I want that my player follows automaticly a path, but with just points, he dont going very smooth trough the Curves. So i installed the path Creator. But now he follows a path, but he doesnt collide with the ground or anything else. Does anyone knows how to fix this? Or is there a better method out there for following a path
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Don't call MovePosition on rigidbodies that you want interacting with other rigidbodies or other colliders in general
it breaks the simulation.
it doesn't break it but don't expect any rotational forces to translate
meant position, not rotation
@winged dagger did you even drag the script onto a gameobject in the scene
this feels like you heavily just copy pasted the code without understanding a single thing about it
@cobalt wave yes
@winged daggerThere's really no reason to be scaling by deltaTime in fixedupdate
yes i copied from the website that was showing the inctructions for that project
yea, if you are gonna do deltaTime scaling use fixedDeltaTime
time.DeltaTime returns time.fixedDeltaTime in fixedUpdate()
still, no reason for it here
its the official unity website so its nothinhg with the code
I'm sorry but I won't be explaining you code you copy pasted from the internet
if there are instructions, follow them
did you get any errors?
did you hit play?
yes i hit play
there could be so many things that you did wrong, you need to narrow it down for us
i added tht script to the component as well
I mean, what's the problem?
All you did was paste code. Not explain what's not working
my character is not moving
probably because you're moving it in the animator callback for whatever reason
Your character also isn't going to collide with walls using MovePosition
it will collide but it will be clip in and out
and everything in that script is viable tbh
nothing should make it not work
this really comes down to what you did in the editor
his animator callback is the reason it's most likely not working
you shouldn't move simulation objects like that anyways
can you point out specifically what i should remove or change in my code
already did about 3 times
If you can't figure it out, then perhaps it's time to learn C# instead of just blindly copying things from chatGPT
lol
this is my first time using unity
If you don't want to learn code, then there's really no reason to be here
Then why do a programming related course ?
nobody is going to write your school assignment for you
and it's dumb that you would think that
guys
i tried fixing the pickup code
now it cannot equip
i can drop
but i cant equip
elaborate
i want a code where i can drop a gun and pick it up
so i tried to code it
before it worked, but it came at the wrong side
now it doesn't even work at all.
maybe share the !code?
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I can't seem to figure out why my plugin is not loading for android.. I have gotten it working for nearly everything else so far but for android I'm getting a dllnotfoundexception
so im making a car controller in unity and have everything set up but when i press play the cars wheels move out like this:
i know what part is causing the problem, its this code:
but im not sure why its doing that. can anyone help?
guys?
@small lodgeI've had this issue before
your wheels origin isn't centered
you need to fix it in blender
when you click on the wheel, the transform should be right in the middle
Is there any reason why code isn't being ran correctly in a build for the quest 2? In editor it looks just fine though.
Basically I'm just copying the mesh of an object to another however it does not show up in the build.
Usually differences in a build are from script execution order differences or framerate dependent code
// Setup a clone of the held object
if(clone.gameObject == null)
{
// Create object and components
clone.gameObject = new GameObject("Clone");
clone.filter = clone.gameObject.AddComponent<MeshFilter>();
clone.renderer = clone.gameObject.AddComponent<MeshRenderer>();
// Copy values to the cloned object
clone.filter.mesh = heldObject.GetComponent<MeshFilter>().sharedMesh;
clone.renderer.material = material;
clone.transform.SetParent(transform);
clone.transform.SetPositionAndRotation(transform.position, transform.rotation);
clone.transform.localScale = heldObject.transform.localScale;
}
Clone refers to a struct containing information about a gameobject and acts as a hologram of a held object.
This is called while the held object is within a trigger using OnTriggerStay.
Weird. Thank you for sharing!
if anyone has any experience with this or any clue for what I could be doing wrong I would love to hear it. I'm all out of ideas to try. Any help is greatly appreciated
Is your plugin designed to work on android?
If it's written in native, then it's probably doing something android doesn't support
Yes I have tried compiling it for both arm64-v8a and armeabi-v7a versions
would anyone know how fix this? apologies but i think expressions fall into the coding?
for the cinemachine virtual camera, how do you change the Follow Override with code?
did you look in the api docs?
This is not particularly unity related.
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
now guys
how do i only disable the firing and reloading part of the code of the gun when it is not parented to the player?
Likely a beginner question. Also it's not really possible to help without seeing the code since theres a ton of ways how u couldve coded it. From what you've said, I assume your gun script directly takes the input, instead of the player calling the shoot method
If statements!🪄
yes, wait ill input the code
yeah, i dont know how to code parent variables
transform.parent, GetComponentInParent(), etc...
This is really #💻┃code-beginner level question. Or even just a Google question.
yeah, thanks
sorry
this is also just not a good way to code your gun functionality
how do i improve it?
your guns right now are dependent on the user input, when its functionality should be called when the player presses to fire it. This would also allow u to have other things like an enemy fire the same gun
so i should use a function
right now u would have to either disable this script, or have an if statement constantly checking if its parented to the player to determine if its running. By having the player fire the gun instead, its just one check to see if the player even has a gun
"use a function" doesnt mean anything, im saying call the guns functionality from the player
problem solved it was an api mismatch. the default api version I was building some shared libraries for was higher than the current android version on my phone
is there a way to do a chain .Intersect on n number of lists? I have a list-of-lists and I want to get the elements that are common to all of them. Is there something in Linq that does this for more than just two given lists?
hashtable?
There might be a better way, but maybe .Aggregate() your list of lists, intersecting each with the accumulator value?
Looks promising, thanks!
so if I have List<List<T>> list; and I do something like list.Aggregate( (list1, list2) => list1.Intersect(list2) ) should work, and List1 is whatever the result of the previous function returns?
weirdly I've gotta cast the interect back to List<> instead of IEnumerable but whatever I guess.
yeah that's the gist of it 👌 - it works like Array.prototype.reduce(), if you're familiar with JS
oh.. the base type here is abstract so it has to have a real type.
oh hmm 🤔
it's no biggie, it's only because I'm trying to create the initial list with a concrete entry
I have an error pop saying a reference is null, the game pauses on the error, and in the inspector the reference is visibly not null. I am also 100% certain its the only instance of the script in the scene, checked by code.
likely a #💻┃code-beginner but show code in there because its not possible to help you without more info
best i can say is you have a null reference, and its not where u think it is
i checked by code, I am 100% certain its the only version of that script in the scene. it really seems like there is some sort of corruption
an error freezes the game and I can see the references set when its paused
this barely shows me anything, if its corruption then try making this in a new scene and slowly add everything from your old scene until the same error happens. If it does not happen, then its either a unity bug or you missed adding something very small
Please show the full error including stacktrace and also the code that it points to at the top of the stacktrace
Can some1 help me with IK foot placement?
If you have a direction and a distance then you can get a position, so perhaps using lerp or MoveTowards is what you're looking for.

so i need a little help with my code, im trying to make a fps-character. it worked fine but when i added the wallrunn features it kinda broke down and i dont have any gravity anymore (im just static floating)
Ehh, the !code as you share it is annoying to read, maybe use a paste site.
That said, if your gravity gets messed up, then you should probably apply Debug.Log statements around the code and see where it goes wrong. It also allows you to see the steps taken.
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
anyone have an idea for a vr game
Hi, does anyone know if it's possible to merge multiple colliders? I have a script that merges all children objects' meshes into a unified mesh, and I would like to save some time by not having to reapply every collider. thanks.
Fixed it i was missing discord.RunCallbacks();
there is a composite collider for 2D physics, in 3D your only option is a mesh collider generated from the combined mesh. Performance wise it is in most cases preferable to use a set of primitive colliders over a mesh collider. All colliders under a rigidbody will be "combined" automatically as far as the force simulation is concerned.
yeah that's what I thought. I am combining my tiles into a single mesh, and using a mesh collider will effectively quadruple the amount of vertices on the collider
not sure how well that performance deficit translates into the real world tho
why doesnt this work? it looks like it should:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collide : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("lazer"))
{
Debug.Log("You got hit!");
}
if (other.CompareTag("food"))
{
Destroy(other.gameObject);
Debug.Log("Points! +1");
}
}
}
make sure your tag is exactly like that. it's case-sensitive
There is a resource for physics messages pinned to #💻┃code-beginner that you can follow to debug this
alright
what shape tiles do you have? if they are cube/quad, just use box colliders and dont worry about combining them, you can have a lot of static colliders in a scene without any noticable effect on performance if your game's action is localized
they are cubes, but they are often intercepted by doors in between, which needs to be passed through
so you end up having to place 5+ colliders for every room in the building
how many boxes would that be in total?
for the whole level?
yeah
so mesh colliders should be fine then?
a mesh collider will probably be worse, performance wise
no, make boxes
but even mesh colliders wont cause issue (most likely)
or put another way, if either the mesh or box collider approach will cause performance issues on your target platform you need to rethink your design anyway, neither of them will likely fundamentally change your performance if your levels are too big or too dynamic on a large scale
in general, the physics engine is very good at only evaluating collisions in the local space that your are performing actions in, so if you avoid any collision checks in areas of the level that aren't observed by the player, you can improve your performance drastically (assuming large levels that are only partially visible)
I'd very much like to take the extra step for performance, but unfortunately I'm on a bit of a time crunch. Levels aren't really too big, so I think it's gonna be fine for this project. Thanks for your insight tho
is it a mobile project?
nah, pc
then you are most likely fine
would someone know how to make a movement system like this?,i tried many ways but couldn't get it to work my latest try was
private void SetRotation()
{
transform.Rotate(Vector3.forward,_input.MoveX * Time.fixedDeltaTime * _speed.Value);
_rigidBody.rotation = Mathf.Clamp(_rigidBody.rotation, _minRot, _maxRot);
}
I'm sorry I don't understand your drawing. can you explain the expected behavior?
basically,the player can rotate their rocket into a certain direction by using the left and right movement keys(A/D,←/→) and be able to move up the direction they are facing
I see. I'm guessing this is a 2D game?
yes
to start with you never modify the transform and the rigidbody, you need to chose one or the other
Steve is correct. To know which one to use, you need to consider whether or not you intend to use physics in your controller.
yes i intend to use physics
OK, then you'll want to use the rigidbody and not manipulate the transform directly
private void SetRotation()
{
_rigidBody.MoveRotation(_rigidBody.rotation + _input.MoveX * _speed.Value * Time.fixedDeltaTime);
_rigidBody.rotation = Mathf.Clamp(_rigidBody.rotation, _minRot, _maxRot);
}
should this work?
is the clamp intended to set hard limits on how far you can rotate?
yes
about 45 degrees
I tried this,it didn't rotate at all
I think you probably want to use the rigidBody.SetRotation() method in your case
The downside of this is that there will be no "coasting" after the buttons are released.
I'm trying to hit this object here with a raycast
it's a curved plane, but it's not being detected
if I create a plane with the same size, it detects
normals are fine, and I tried shooting the rays from both directions just in case
it works when I add a mesh collider with the same mesh
any clue on how to do it without the collider? I can hit other solid objects just fine, but curved planes are being a problem
coasting?
like after you release the turn button. do you want it to stop rotating instantly or have some "driftiness" to it?
i will see later,thanks for the help but there is another issue
the controls are inverted,the input action asset controls are right but rotating turns it in the opposite intended direction,even in the editor
wait
right is -45 degress,when it should be 45
negative Z rotation seems to be clockwise in my editor as well. Why do you feel this is inverted?
usually,right is positive,while left is negative,i have no idea why it does this,i don't even remember it doing this before
I think the reason for it being that way, is that in 2D mode the camera looks in the Zpositive direction so that elements Z position increases as they get farther from the camera, which I think is more intuitive. If the camera forward is Z positive then negative z rotation must be clockwise
As far as I know, the Physics.Raycast method can only raycast to colliders.
When I set objects to hide for a long time in the editor, I can't unhide them. Anyone know why? Fixes after a restart
0 is positive,right?
Haha, mathematicians have been trying to figure that out for centuries. But I'm sure that's not what you mean. In what sense do mean 0 is positive?
0 is forward
z specifically
I see, you mean is 0 Z rotation forward?
yes
is the sprite upside down/scaled negatively?
well. In your game, when you say "forward" you mean "up", right?
in the rocket?yes,in the camera?,no
i can see that you are rotating the parent, but not too sure whether the sprite is on a child of the parent or something
they are made using unity 2d primitives,and nothing is negative,but let me check
ah i see
they are all positive,smallest is a decimial but not negative
it is a child,there are multiple sprites
couldnt tell they were primitives 😅
and by default it’s not upside down right?
wait i misunderstood the question
you mean the shapes?,no
If I understand what you're asking, then I think this is answer you're looking for. If you set your rocket's Z rotation to 0, it should be pointing straight up.
yes,but when it i press the left key to rotate left it goes right and vice versa
in your code you are getting the input, multiplying that by deltaTime, multiplying that by speed, and then adding that all to the rotation. Try subtracting it instead
or you could go into the input manager and switch the inputs around
