#archived-code-general
1 messages ยท Page 439 of 1
i need to have an object be "parented" to another object, have its rotation and position change relative to its "parent" without actually being parented to the other object i believe the best solution for this is to have an offset and changing the "childs" position based on the offset. this is the code i tried and i fully understand why this code doesnt work but i just cant seem to wrap my head around how to apply the solution to make it work
private void FixedUpdate()
{
var pos = transform.position;
_offset.x = Mathf.Abs(pos.x - parent.transform.position.x);
pos.x += _offset.x;
transform.position = pos;
}```
aight so uhm how can I improve this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class CharacterAnimations : MonoBehaviour
{
private Animator CharacterAnimator;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
CharacterAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (CharacterAnimator != null)
{
if (Input.GetKeyDown(KeyCode.W))
{
CharacterAnimator.SetTrigger("TrRun");
}
if (Input.GetKeyUp(KeyCode.W))
{
CharacterAnimator.SetTrigger("TrStop");
}
if (Input.GetKeyDown(KeyCode.S))
{
CharacterAnimator.SetTrigger("TrRunBackwards");
}
if (Input.GetKeyUp(KeyCode.S))
{
CharacterAnimator.SetTrigger("TrStop");
}
if (Input.GetKeyDown(KeyCode.D))
{
CharacterAnimator.SetTrigger("TrRun");
}
if (Input.GetKeyUp(KeyCode.D))
{
CharacterAnimator.SetTrigger("TrRun");
}
if (Input.GetKeyDown(KeyCode.A))
{
CharacterAnimator.SetTrigger("TrRunBackwards");
}
if (Input.GetKeyUp(KeyCode.A))
{
CharacterAnimator.SetTrigger("TrStop");
}
}
}
}
Input.GetAxis
what the hell is that

You should also use blend trees for easy blending between many animations on a 2d axis: https://docs.unity3d.com/Manual/class-BlendTree.html
its 3d
you can have another layer that overrides with its own 2d blend tree?
I have no idea what that means but the game is 3d
HA okay go read the page and then come back
oh I have heard about blend trees
These should be used instead of the crud you showed above.
e.g. input horizontal + vertical to blend between forward/back/left/right movement anims
i think the unity pre made examples use these
Okay, so?
so not this?
no, the doc page explains it....
๐
its 2 am
blend tree gets rid of so many arrows
yes yes have a sleep and come back with a fresh mind
Any way to make this happen with TextMeshPro? Like different colors and sizes within a sentence? Maybe with icons in it as well?
yes Rich text
for sprite is just <sprite> but you can scroll through list there is so much you can do including clickable links
I presume ui toolkit can do this even better with <span> ?
Awesome, thank you!!! So the tag just go in the textmeshpro text box itself?
would assume if it works like CSS.. hmm I need to start messing with UIToolkit again besides Editor utils/assets
yes
TMP internally parses the tags
Perfect!! Thank you!!
yeah ok so calling this in builds on a mesh that is NOT readwrite errors:
I guess maybe it's not meant to be. What's the usecase?
Do you mean what am I using it for, or how I am using it?
What game functionality or system are you trying to set up that you need to do this?
I just need to be able to load meshes in builds
its for a plugin/asset I am working on, and I dont want to require the user to set all meshes to be readwrite all the time, even procedural meshes
especially since some meshes you cant change that on(some GLB importers you have to modify the importers code of to get their meshes to be readwrite)
But it seems like you need to read the mesh data, so wouldn't requiring the mesh to be read/write be a reasonable requirement?
You could also have your plugin set it to read/write in the editor (perhaps with some warning, or prompt, or user action to ask for permission)
is there an easy way to set every mesh in a project, even procedural ones or ones generated by custom imports to readwrite?
it just really seems like there SHOULD be a way to read non readwrite meshes in builds
in editor play mode, I can do GPU -> CPU readback, why cant I do that in builds tho?
it just seems really weird that an important part of reading meshes on the GPU for rasterization seemingly doesnt exist in builds
You can search for all mesh assets like this: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AssetDatabase.FindAssets.html
in editor play mode, I can do GPU -> CPU readback, why cant I do that in builds tho?
I'm not sure why. I know in edit mode it's always accessible by design.
but in meshes, readwrite is a ReadOnly property
you cant change that from script afaik without creating a new mesh, copying the data, disposing of the old mesh, and saving the new mesh, which feels like itll cause hell in terms of asset linking, could mess with custom importers(especially if you import from blender directly and modify the blender file later) and could take a LOT of ram
It looks like the way some people do this is actually modifying the asset file text
https://discussions.unity.com/t/setting-read-write-to-false-on-generated-mesh-asset-in-editor/879916
ewwww
thats a nasty workaround
if the mesh is readwriteable I can get the indexbuffer tho I think,
so I can at least handle skinned meshes like that
but still
Looks as though it can be set from a ModelImporter - aka plugging into the asset import pipeline https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ModelImporter-isReadable.html
for reference, this is how I get the index buffer, where TempFilter is a MeshFilter that is known valid:
mesh = TempFilter.sharedMesh;
mesh.indexBufferTarget |= GraphicsBuffer.Target.Raw;
GraphicsBuffer indexesBuffer = mesh.GetIndexBuffer();
can that be done after an import from a seperate(say lightwave, or glb, or dae) importer is done?
but yeah it doesnt say anywhere in the api documentation that indexbuffers dont exist for non readwrite meshes in builds
I'mn not an expert on asset importers. I would ask #โ๏ธโeditor-extensions
urg
it just feels like it would be a workaround solution when there really should be an easier way
I cant believe tho I am the only one to run into this issue it seems, really makes me feel like there IS a good solution that I just dont know about
the only post relating to this is my own post from two years ago on reddit
there IS GetNativeIndexBufferPtr
but can that be resolved back to a graphics buffer in unity?
How do people handle "block durability" in voxel games?
I don't really care for blocks "saving" their durability in the chunk data itself.
My idea was to spawn a 1.01 scaled voxel inside a voxel with the "animation" texture whenever you first click it.
If you click it again, it subtracts from its HP.
Once its zero, it deletes the animation block, as well as block it spawned inside.
Im doing this with an indicator as well. Just hiding/showing instead of deleting.
Is there an easier and/or better way to do this?
ok this will be fine. I dont really care if theres another solution anymore tbh lol.
worst case scenerio, I have 20+ blocks that are in the "breaking" stage.
A block will only hold its durability for a few seconds before it "heals" itself and deletes the "block breaking" gameobject.
I just need to use a shared material for each "block break", and offset the texture by its current stage
Not sure where to ask but this is more-so just a curiosity about Unity that I know at this point they absolutely can't do
Given that tags and layermask definitions are so hardcoded and can't be adjusted at runtime, Would it have been reasonable at some point for Unity to automatically generate and manage a c# definition for this to be referenced explicitly in code rather than constant juggling of ints and strings?
Or is that a fairly outrageous pitch in the context of more sophisticated programming
Outrageous.
Although it would be a good idea to have them somewhere stored as static field:
public class LayersHelper {
public static int Player = LayerMask.GetMask("Player");
...
}
that's somewhat what i meant yeah
yeah what I mean is we do this already ๐ Pretty much every game has this class in one form or another, and I was recommending you do this too.
i guess it's probably just a very low priority for them, the layers system being string based is good for beginners because it's so simplistic
Respectfully wasn't asking for a solution ๐ It's not a problem I have
Just was curious on why Unity may not have
Gotcha. I'd say it's overengineering. Saves maybe 5 minutes per project, and adds an additional dependency (the auto-generated code)
there's stuff like do you want every layer/tag change to trigger a domain reload, or do you need to worry about syncing it manually and it going out of sync, which they don't have to care about if they just let you implement it yourself
rather than storing block durability for every block(that's maybe 4 bytes per block in the hundreds of thousands), you can just have a List of block positions and their durability.
Your scaled voxel is also a good idea
minecraft AFAIK only has block durability for a single block (the last one you hit)
I got it working pretty well.
I'm storing a dictionary of "damaged blocks" by their position.
When "mining" something, I can just call "damage block" at that position with a damage amount.
If the block hasn't been damaged, it will be added to the dictionary, a recursive invoke function will start "regenerating health" until full, then delete and clear that block from memory.
Yeah I'm pretty sure MC just cares about the block you're viewing per tick.
I want stuff like "explosions" that literally simulate the explosion itself, leaving a damaged crator.
Or blocks that could "burn" to death showing durability.
Mining isn't even the main idea of my game lol. But I figure i might as well develop the sandbox a bit now vs later.
For any kind of per-voxel data you always have essentially two choices:
- a 2D array
- a Dictionary.
The Dictionary is better for sparsely populated data and the array is better for densely populated data. This durability thing sounds very sparse.
Is there anyway to do something like this where it doesn't get messed up down the road by i being in there? Basically I need a way for it to convert i into a primitive integer in the function, so that it can actually be called later outside of this loop and without using the final value of i for all the actions.
int temp = i; then use temp in the lambda
That feels super dumb to do, but it worked, so thank you!
Turns out the issue has nothing to do with URP/camera/changing values at runtime/etc, but instead the custom UI shader is missing:
ZTest [unity_GUIZTestMode]
It doesn't seem to be documented anywhere and the effect of missing it is very subtle, only causing shader to not work under very specific circumstances, which caused me to think it was the code triggering those circumstances to be broken, but it's actually the shader all along and it just happened to not show symptoms until now.
Got scheduled for tools programmer interview. I have some experience in .Net (Asp.net mvc, Xamarin Mvvm, Winforms ) and QA roles and have made some games in Unity during my career gap. I just want to know that whether the interviews are tough and what are the questions that I might face? Need some advice if any.
So I am remaking King of Crokinole (was my 1st game and it would cost more time to fix than to rebuild) ... One of the things that messed things up were these forced engine upgrades I had to do to comply wit Google Play &Apple policies (billing libraries and such)... so I was wondering if and if so how I could have these platform specific upgrades outside of the main app (like addressables or even separate packages) ... also these build levels (for Android are a right pain)... I mean how do the pro's deal with this?
Anyway enjoy a w.i.p. as well
First off congrats!
My advice would be to just be yourself ... personally I tend to go into these things under the assumption I am not gonna get it , takes the edge off .
The fact that they called you in is already a good sign though.
So relax
Vector3 moveDir = transform.forward * moveAction.ReadValue<Vector2>().y + transform.right * moveAction.ReadValue<Vector2>().x;
rb.velocity = moveDir * movementSpeed;
trying to put the rb.velocity.y into this fps movement line, how would i go about this?
because rn it only falls down really slow because there is no y axis defined here
Vector3 velocity = moveDir * movementSpeed;
velocity.y = rb.velocity.y;
rb.velocity = velocity;
works! thank you vm Nitku.
how to make some sort of a temperature map on a 2D grid?
float[,] temperatureMap = new float[gridX, gridY];
i mean how i can bind it to tilemap
so the 'cells' could react to hot zones
ah. Well, you can either make a custom tile that accepts a Temperature parameter, or use custom OnCellEntered logic.
custom tile?
i want tilemaps because cooking phones is not in my plans...
i mean my field sizes are 8028 by 2004...
and +mp....
so how i could sync it?
well, how do you sync other stuff? e.g. Health?
syncvars
but im mp rookie...
Mirror.Weaver.ILPostProcessorHook: (0,0): error Single[0...,0...] is an unsupported type. Multidimensional arrays are not supported (at System.Single[0...,0...])
try float[][] then
1 sec
Assets\Scripts\Netvars.cs(9,48): error CS0178: Invalid rank specifier: expected ',' or ']'
cmon man you can figure this out by yourself -- google How to init 2D float array
float[][] temperatureMap = new float[gridX][];
for (int i = 0; i < gridX; i++) { temperatureMap[i] = new float[gridY]; }
how to setup gitlab CI with build and unit tests for a unity project?
guys i try to teach and i find flappy bird tutorial dont hate me is my first and i cant make random.range
You'll have to tell what the error message is
I guess error is that Random is ambiguous so u have to say UnityEngine.Random
thanks i try
ehm
Your parentheses are misplaced
Range creates a single number between lowest point and highest point
no 3rd argument
oh
maybe u wanted that 0 outside of those parantheses
You are missing a comma , and a parenthesis ) as the errors say
You're not closing the new Vector3( here
yo i got it
Maybe don't do it all in one line if it's gonna be difficult to keep the parenthesis straight
Your code doesn't get any faster if it's one line versus multiple. Primitives and Structs cost the same amount of memory whether they're given a variable or not
guys, I came back with trying to make that puzzle where you clean your PC by removing the coffee you've spilled on it, so I started with the mouse position recognition, but it doesnt work at all, check out my script:
public class CoffeePuzzle : MonoBehaviour
{
public Camera cam;
void Update()
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit)) {
Debug.Log("Acertou: " + hit.transform.name);
}
}
}```
is there a 3d collider that is in the direction of this ray?
it's 2d
the only colliders I have in the scene for now is the player and the object I want to recognize
well no wonder Physics.Raycast isn't working then
oh so what I use then?
take a look at the documentation and maybe you'll see what you should be using for 2d
but also you don't need a ray at all, an overlap point would be sufficient
when I searched to make this script there was nothing saying: "This doesnt work for 2d, use x instead"
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I was wanting to know if I am casting the sphere cast correctly for ground check.
https://paste.ofcode.org/6uGtXACKY8NmTsGMbxDT7V
also any code improvement's I can make.
seems to be fine
That is correct, Physics.Raycast is for 3D physics. Physics2D.Raycast is for 2D.
(I have already asked this is #๐ฒโui-ux but I am unsure if the way to do this is code-related or not, so I am sending it here as well.)
Hey so, Im working on a TD game. I want to have a small UI element like this as a buy/upgrade menu, and I want to ensure that it does not go off-screen.
How can I ensure that the menu appears above a tile when a bottom tile is selected and vica versa, like this example?
(Example from Mini TD 2)
Vector3 thisVelocity = rb.linearVelocity;
why does this throw a null ref error? what am i not seeing?
rb is null
if that was the case then my get component would be the one throwing the error, not this
nope
that is incorrect, GetComponent does not throw if the component does not exist on the object, it just returns null
oh whoops
heh
this is called a pipe character or vertical bar, it's location on your keyboard entirely depends on your keyboard's layout
thanks
it's backslash
does the pipe character always share the same key as the backslash? thats where its located on mine
i feel like ive come across keyboards where it isnt
how can i make the camera look at the mouse position in 3D? ive been using this code that i found as a temporary solution but its clunky and it doesent really follow the mouse position also its a very bad use of the lerp function but for some reason it only works this way,dont ask
rotation.x += Input.GetAxis("Mouse X") * 10; rotation.y += Input.GetAxis("Mouse Y") * 10; var QuatPosX = Quaternion.AngleAxis(rotation.x, Vector3.up); var QuatPosY = Quaternion.AngleAxis(rotation.y, Vector3.left); transform.rotation = Quaternion.Lerp(QuatPosX * QuatPosY, transform.rotation, Time.deltaTime * 60);
i tried using something like
camera.main.screentoworldpoint(input.mouseposition)
but for some reason that doesent update at all,the position seems to remain at the world origin and moving the mouse doesent change the coordinates of that
ehm ehm help?
using UnityEditor;
[CustomEditor(typeof(PlayerController))]
public class PlayerControllerEditor : Editor
{
SerializedProperty gravityStrength;
PlayerController playerController;
private void OnEnable()
{
gravityStrength = serializedObject.FindProperty("gravityStrength");
playerController = (PlayerController)target;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawDefaultInspector();
if (playerController.enableGravity)
{
EditorGUILayout.PropertyField(gravityStrength);
}
serializedObject.ApplyModifiedProperties();
}
}
Is there a way to remove fields after they have been drawn?
This adds a second field if the boolean enableGravity is checked, but now I have either one or two gravityStrengths. How do I remove the one drawn by DrawDefaultInspector?
well, what does the warning say?
wait i try it remake
well, that's a different thing
you need to configure your !IDE if it isn't showing errors in the code๐
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
also, what's with that Obsolete annotation?
so did you read the warning message?
i mean, GameManager should probably be a singleton anyways, rather than you Finding it every time you need to access it
ohhh
another problems
BTW Thanks
i ts ok
i fix it
If i wanted to create a large open world sandbox type game, how would i organise and structure my scenes?
Im using a character controller for controlling my games player and i have a seperate script that moves the object as if it were parented to another object which can be anything, the problem is the script works fine when i try to use it with a simple object like a cube or sphere but when i try to use it with the player whether it has a rigidbody or a character controller it just doesnt work properly and seems like it doesnt move as much as it should and ends up lagging behind the object its "parented" to here is my script for it
using System;
using UnityEngine;
public class FollowParent : MonoBehaviour
{
[SerializeField]private GameObject _parent = null;
private GameObject _lastParent;
private Vector3 _offset;
private Vector3 _lastChildPosition;
private void Start()
{
if (_parent != null)
{
_offset = transform.position - _parent.transform.position;
_lastChildPosition = transform.position;
}
}
private void Update()
{
if (_parent != _lastParent && _parent != null)
{
_offset = transform.position - _parent.transform.position;
}
if (_parent != null)
{
if (transform.position != _lastChildPosition)
{
_offset = transform.position - _parent.transform.position;
}
else
{
transform.position = _parent.transform.position + _offset;
}
_lastChildPosition = transform.position;
}
_lastParent = _parent;
}
private void OnTriggerStay(Collider other)
{
if (other.CompareTag("Ladder") && Input.GetKeyDown(KeyCode.F))
{
_parent = other.gameObject;
print(_parent);
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Ladder"))
{
_parent = null;
}
}
}
when making one object follow another you typically want to update the following object later than the object it is following, one way to ensure that happens is to update the following object in LateUpdate rather than Update
it still doesnt work even i put it in late update i just had it in update to test if that was the issue for whatever reason
whats weird is if i disable the character controller it stops it from lagging behind
Hi, can I get a sanity check? Is BlobHashMap in Unity.Collections? I'm using 2.5.3, if that helps
@placid ridge What is the issue?
Add logs. I can imagine that your offset changes every frame
it does but only if it was not the same as the last, why would that be an issue
Because it's happening when you don't want it to happen
If the offset were to change every frame the following object would start lagging behind.
i want it to constantly update, it works fine if i have it on an object without a character controller
You're not trying to understand what I'm saying.
Add logs and see for yourself.
I'm trying to do some vibe coding and the Gemini LLM is insisting that BlobHashMap exists. I don't think it exists in the official Collections package, so I'm probably going to switch over to a list since the performance impact isn't large, but at this point, I just want to know if BlobHashMap really doesn't exist in the official Collections package ๐ Thanks, by the way
You can check the docs for that...
I did, but I'm new to Unity (but not coding) and am still learning the ecosystem. And sometimes docs don't have a perfect coverage of what's in a package. Rare for larger projects, but it does happen!
added logs, it updates only when the parent changes and when the object moves not sure what you mean by its not updating when i want it to, if you have a better explanation it would be great
If it's not in the docs, they probably don't want you to use it.
Hahaha that's a good point
When does the offset update?
only when the parent changes and when either object moves
Well, should it update when the parent object moves?
Shouldn't it follow the parent with the same offset to keep up?
yes, though it is never actually parented to anything im just simulating it being parented
thats exactly what the code does
Well, try commenting out the second offset update line. The one that runs when the object position is not equal to previous position.
And see if the lagging behind happens.
that will just constantly update the position of the object and while the object will follow as if it were parented, it wont move independently in its own local space and i might as well just put a parent constraint on it
Yes, that's right, but just do it for testing purposes.
it does what i said in my last message
So it stops lagging behind?
yep
Great, so now you know that setting an offset there is the cause of the issue. Now to understand why that happens.
So back to logging. It must be setting the offset when you don't want it to be set(i.e. when the object is not moved by anything and just follows).
I really don't understand why we need to do this debugging 101 session here. This should be in #๐ปโcode-beginner
You should always look up <thing> Unity when dealing with AIs because they like to pull info from github as if it were official
BlobHashMap exists but its in fact a github package
Yeah, that's what I'm finding. It's fun to code with LLMs, but they do have their limitations.
because im pretty sure this doesnt have to do with what youre telling me and something deeper with how the character controller works because it works flawlessly on objects without a character controller and could also be something to do with netcode for game objects though i really dont think thats the issue and this honestly hasnt cleared anything up ๐ thank you for the insight though
Reminds me of the Color.distance incident where someone posted code using this made up method.
You should really not be using these tools especially if you dont know the basics of unity yet.
I mean, usually yeah, but I've been coding for over 20 years with tons of experience in larger scale groups. Coding with an LLM is no worse than coding with an intern who makes a lot of mistakes, but can give you insights into how systems work. As long as you structure your code to fail fast, it's not an issue. I've been coding with LLMs for a bit now. They can really speed up your work, but you have to stay aware of how they like to fail and what it looks like. But I must admit, coding for newer stuff with an LLM is certainly much more risky than it'd be if I were dealing with an older system.
Plus they can introduce you to new, more efficient practices at times.
The amount of time you wasted just now on verifying its hallucination probably already offsets whatever it saved you.
Not really, no
If you're working in stuff which is adjacent to your knowledge, they offer huge speed boosts
Plus the overall quality of simple code is usually the same as your own code, or sometimes higher
I'd highly recommend LLMs for simple code.
For more complex and adjacent stuff, they are excellent tutors at a minimum.
Using LLMs to write code is like babysitting a junior that never improves no matter how long you mentor them. But well if it works for you then go for it then.
but you have to stay aware of how they like to fail and what it looks like
Which is exactly what my message is telling you, you dont know the basics. You couldnt even tell if the AI code was valid.
But code is usually the same across most systems. Modern IDEs do a good job for telling you if you're about to go off a cliff
I mean across majorly different systems
Network code, cloud infrastructure, etc. There's a huge amount of overlap
If you have enough knowledge from enough systems, you can start to spot sus code when it happens
And for that, that's what testing is for
Not all problems can be caught by IDEs, case in point the nonexistent API you were asking just now, because IDE cannot possibly know all the packages Unity has.
The thing, it takes half a second to see a red squiggle and investigate. From there, it's a simple substitute for what's causing the problem. It took the LLM 5 seconds to spit out the whole code segment. It took me a minute to read everything, verify it looks somewhat right, then check it. Sure enough, there was a simple error which can be caught. The logic was sound. If I had to write that by hand, it would have taken me 10-15 minutes, but because this is adjacent knowledge, I would then have to spend another few minutes searching for the exact types I can use and whatnot. I can understand the pushback against using LLMs, but not using them in 2025 risks putting people behind the wave, yknow?
Ok, so there's a lot of relevant context that you didn't mention initially. Like networking being involved.
I'd suggest getting it working in a single player setup first.
However, the fact that the bug doesn't happen when that line is commented out clearly tells us that the changing of the offset occurs when it shouldn't. Or has values assigned that are not correct.
And suggesting using the llms indiscriminately to beginner risks making them entirely depend on the llms and not able to do anything by themselves.
Though, this is not a beginner channel, there are still many beginners here.
I think llms are great assistants, but one when you know how to do it yourself
Otherwise it's the same as copying code blindly from the internet
I agree with those points, but as a heads up, I'm not advocating for beginners to use LLMs.
But for experienced coders? Yeah, they're good if you know what you're doing
Just saying, most experienced devs here are going to suggest against using it for the general public, even though they may use in some aspects. You aren't gonna convince anyone here that you should be using it. The conversations became so frequent there is a dedicated forum for it https://discord.com/channels/489222168727519232/1352599815770341479
Still, the suggestion for you is not to use it. You are a beginner currently in unity!
and you really aren't helping your point considering your issue was if the code even exists.
Thanks for the heads up. If I feel like continuing the convo, I'll hit up the forum. ๐ I'll drop the topic now.
I have heard that lerping towards values with the variable as A is bad
Because it never reaches the final value or something (even though it actually does)
What is the alternative, though? The most common solution I see is to ground the time at some point from when the lerp starts, so you're doing timeElapsed / startTime
How would this be applied to multidirectional movement? You don't exactly have a point of reference to go off, especially not since the player can be pressing any combination of WASD and you can't just keep resetting the time
Wdym by "with the variable as A"?
This doesnt really make sense. A just represents the first variable, the start position.
A common mistake is doing transform.position = Vector3.Lerp(transform.position,...,...)
Because this is no longer the start position, it's the current position. The T variable is a normalized value between 0 and 1 which is essentially a percent of how far it should be from start to end
speed = Mathf.Lerp(speed, newSpeed, Time.deltaTime);
This doesn't answer my question. I don't see A anywhere in this code.
Lerp has (A, B, T) as parameters, sorry
Yes, but this doesn't exactly help if you need a way to smoothly move towards a value. What is the problem here?
Time.deltaTime also doesnt make sense there but I described why above in the same message
It does, I described 2 problems which both apply to the code you sent
You are using the current speed, not start. Your T parameter doesnt make sense here either
Ok,but that still doesn't explain anything. Do you perhaps mean that the third parameter(time) is not moving between 0 and 1?
You just stated two facts about the code. What problem does this cause?
if you want it to go smoothly from A to B over a set time, you store what the start is and have T go from 0 to 1
currentTime += Time.deltaTime;
normalizedTime = currentTime / totalDuration;
speed = Mathf.Lerp(startSpeed, newSpeed, normalizedTime);
Sadly Mathf doesn't have the equivalent of math.remap from Mathematics package.
^-^
public static float Remap(this float value, float min, float max, float newMin, float newMax) => Mathf.Lerp(newMin, newMax, Mathf.InverseLerp(min, max, value));
Sure, but it would be nice if we didn't need to write one.
(Not that I think an extension menthod on float is a good idea either)
Really? What's wrong with it?
Hmm, I supposed "not a good idea" is not the right wording, but foo.DoSomething() has the semantic that it's foo that's doing that something. someFloat.Remap(...) doesn't make much sense, that float isn't doing the remapping, it's being remapped.
Hm, maybe we just see it differently
Like, for example, myfloat.SubtractTen() would clearly subtract 10 from the float, this is intuitive to me
More practically, mesh.FixErrors() would also perform stuff on itself
Even in Unity functions, myVector.Abs() gives you the same vector but in absolute. Nothing unusual about this
mesh.FixErrors() makes sense that it would fix its own errors by mutating mesh itself, so after the call mesh has now changed to be error free
Do you expect someFloat.SubtractTen() to change someFloat after the call?
No, just return the modified float
Just dropping this relevant attribute:
https://www.jetbrains.com/help/resharper/Reference__Code_Annotation_Attributes.html#MustUseReturnValueAttribute
Hello cat
Exactly, that's the semantic difference. It's just like x.Sin() makes less sense than Sin(x).
And in what way is this different? vector.Abs() gives you an absolute vector, myF.Remap(whatevs) gives you that
Okay, the frame dependence is definitely a concern. But you haven't read my original message.
How would this be applied to multidirectional movement? You don't exactly have a point of reference to go off, especially not since the player can be pressing any combination of WASD and you can't just keep resetting the time
I personally think vec.Abs() is not a good API design either.
Well, at least my remap function would be consistent within the Unity API ๐
Something about writing Extentions.Remap(float, this, that, this, that) is so ugly compared to myfloat.Remap(this, that, this, that)
yeah but in this example it's Abs() returning the modified value right? that's not changing the value of vec?
unless im wrong
And mine doesn't either. They work the same in principle.
I did read the original and addressed 2 of the 3 points. I just dont know what you mean in multidirectional. You can use any vector you want.
this example modifies itself no?
That was a bad example.
real ๐
Okay, player is moving forward, and starts moving backwards. If the currentTime is reset here, it would be a jarring change in direction. How does this help?
๐คทโโ๏ธ It would be a jarring change if that's how you code it, and usually that's how games work or your movement wouldnt feel responsive
This feels like a separate problem from asking about how lerp works
Yeah that's kind of the issue of that API design, some calls like texture.Apply() modifies itself, whereas some calls like vec.Abs() doesn't (and instead returns a new copy with the modification)
this is a really fucking dumb analogy but Toast(bread) just makes so much more sense than bread.Toast() imo
because your doing something to the object
the bread isn't toasting itself (except for that one hit indie game)
Yeah it all goes back to the semantic difference of "it's foo that's doing the something" not "something is being done to foo"
I understand how lerp works. Let me make my question more clear, how do I achieve this same effect using lerp the "proper" way?
velocity = Vector3.Lerp(velocity, direction.normalized * walkSpeed, Time.deltaTime * acceleration);
... this still has both of the same problems I described above about using lerp incorrectly.
I gave you a code example above
#archived-code-general message
But it sounds like you might wanna use MoveTowards
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.MoveTowards.html
So your speed can change by a consistent amount per second rather than reaching a goal at a consistent time
im planning for my farming game
lets say the farming game will have 6 big pieces of land with maximum size of 10X20, thats 1200 tiles
if i make a gameobject for each of these grids, it will hurt my phone damn bad right?
so someone has suggested me instead of really making an exact object and drop it into the farmland, maybe i can change the mesh with approximate objects instead
how?
i did have an idea in my mind tho
maybe calculate the ratio of object in each farmland , based on this
get the ID, maybe?
public class Farm{
[field:serializedField] public int height {get;private set;}
[field:serializedField] public int width {get;private set;}
Farm_subsection[,] theMap = new Farm_subsection[height,width];
}
//model class (object)
public class Farm_subsection{
public Crop crop;
public int timer; //active havest timer, in seconds
}
public class Crop{
public int ID;
public string name;
public int price;
public int havestTime; // time needed, 4hrs? 8hrs?
}```
to determine the ratio of spawned meshes(the crops)
for visualization, i would ready for 10-20 sections , only to show crop is there maybe
like if a farmland got 100grid
30 red flowers -> 3 section will show red flowers
20 blue flowers -> 2 sections...
50 green flowers -> 5 sections...
they will still be spawned by gameobject
but that would be less costy than having 200 objects right
any better idea?
Is it 2d or 3d?
Is each tile type just a different texture?
all tile will share the same texture, characteristics
even u can change the skin of the farm, the tiles inside it will be consistent
wait , were talking bout the visualization tiles right?
Sort of. Isn't that what you're worried about?
yes
Anyways, I'd start from using the simplest approach to get it working at least.
Then test and profile on your target device. Perhaps you don't even need to optimize anything.
ok thx๐
Hey,
Im sorry if i interupt you two.
I got an small question: Im trying to make an Room based generation (in 3D) for an small driving game im working on, i want it to be one clear path the player can follow so he reaches the goal at the end, the Problem is, i have no clue how i can avoid loops and collisions without making multiple paths and i also want the path to get a little complicated so he need to do multiple turns and not just move forward, does anyone got an idea how i could achive it.
I can sent my current code if needed but the code is really buggy, like i said its spawning sometimes "rooms/streets" in eachother
I don't entirely understand the issue or what you're trying to achieve, but you have 2 options:
- debug and fix your current code
- go back to the drawing board and design your system from scratch.
If you need help with the former, you should provide more info on the issue(screenshots or videos could help) and the relevant code.
For the latter, you'll need to explain better what you're trying to do and maybe provide examples from existing games/tutorials.
Sorry, I wrote it really unclearly:
So my problem is that I don't really have a clue how to do it in general: I would like to have a system that builds a road based on prefabs, this road should have a clear path without direct branches, so that the player gets from the start to the finish without problems, but the road should also be nicely winding so that he often has to turn off and overall has it a little more difficult. My problem is that I can't think of a way to prevent my road from spawning into each other.
hey ive been struggling for like a day now on this error and i dont really get how to fix it, this happened after i tried to build an android project , the only thing in the scene is the google xr plugin import
i have followed their startup guide and it just keeps popping up no matter what i do
Roads in racing games are often hand designed.
You might be able to implement a procedural algorithm, but it might not be as good as designing by hand. And there might be corner cases that cause issues.
If you really want to go with procedural generation, I can think of several approaches:
- Implement an algorithm that generates the road path. This might be quite complicated. Might want to look up some tutorials or articles on that.
- build the city or some other environment with realistic roads first, and then just trace a path randomly through the environment(on existing roads).
if the city is in a grid you could look at a wave function collapse algorithm but I am unsure how effective that would be
You'll need to learn how the android manifest works and why it expects that resource. Then either remove the dependency from the manifest or add the resource to your project
Share the !code correctly btw:
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ye but i need it to get generated somehow
that would be very hard to achieve tho, because u need to think of height/depth now
i have no idea how that works, i just wanna build a simple scene on android and i cant even pass step 1 ๐ญ
start with building empty project, then work on it, see what breaks it
yeah, thats kinda the problem all its an empty project, all i did was import "google xr"
well google XR is what breaks it then
yeah and then i got that error, ive looked on google and tried most things that people claimed fixxed their issue and mine still remains
have you tried doing what dilch said and removing the unknown parts from your manifest?
i dont really know how to do this im a beginner afterall
well, if you post in #archived-code-general people will expect you to know some stuff
ah my bad then i thought this is like the general chat here
figured it out, it had to do with how i moved the character in the "climbing" state, for some reason having it move in a switch statement i was using messed it up, which to be fair i probably should not have been doing
Is there a way I can blend between two Cinemachine NoiseProfiles? Or change the settings of the noise profile at runtime?
I want to add camerashake, but my previous attempt led to large cuts between camera rotations due to zero blending.
Build a totally new scene, nothing in it. See if that does it. For all you know, this error could happen in that test. Otherwise that's confirmation it's something you later added to the project
ah that scene is like actually empty absolutely nothing is in it but the plugin
like it has 0 objects all default settings
Hi I'm using unity version 2023 and I'm quite near a project deadline, how can I get the old navmesh ?
You mean unity 6? Because 2023 was only as an alpha/beta version.
You'll need to roll back to 2022 if you need the old navmesh I think.
hey guys im trying to create some unit tests for a uni project, and its important that i dont break encapsulation but i still should test certain methods. the solution i tried was instead of making them private, stuff that needs to be tested should be internal so it can be accessed by the unit test, however i cant seem to get it to work?
*im using the NUnit framework if that's important
I know that it would be far simpler to just make a public method that returns that value, but I feel that I'll end up flooding my class with useless methods where there might be a better cleaner solution
Use this attribute to give internal access to your testing assembly
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute?view=net-9.0
oh i was 1 step away lol
thank you
also, is there any downside to doing this? it feels a bit weird changing access modifiers just to test
but idk what real-world issues that could cause
It only affects your testing assembly/assemblies of the same name, so no, other than doing what it says on the tin I don't see what issue you could have
so its basically still private as far as anything outside that assembly is concerned?
Of course
thank you
Personally, I would consider testing only public API surfaces. If WordA is normally unsettable by consuming code, then tests setting it is not really representative of how it's going to be set.
That would be proper, but if there's value in bypassing it, at the end of the day that simplicity can save time and effort
At the cost of long term maintainability though.
are there any downsides to using dictionaries instead of 2d arrays for holding 2d world data? for example, in my survival game, I have a Dictionary<Vector2Int, Block> for my block array, which makes it so that it doesn't have a set size and blocks can be placed at any location. are there any downsides, particularly performance wise with this method?
you won't be able to easily find the bounds of the world from that alone; you'd have to keep that separately for O(1) access and expanding, but you'd still have O(n) shrinking
but whether or not that's important is kinda up to what you're actually doing with it
also, why not use a tilemap?
having an issue with getting an object to look towards a transform point. It works for the right side but when the point moves over to the left it looks in the complete opposite direction and I have absolutely no clue as to why. (game is 2d btw, thats why im resetting the x and y to 0)
public void LookTowards(Transform point)
{
// if (IsFacingObject(point)) return;
Vector3 dir = point.position - transform.position;
Quaternion rot = Quaternion.LookRotation(dir, Vector3.up);
Quaternion finalRot = Quaternion.Lerp(transform.rotation, rot, turnSpeed * Time.deltaTime);
finalRot.x = 0;
finalRot.y = 0;
transform.rotation = finalRot;
}
why does this default to a TMP font material?
"CreateLetterBlockTest (0.161s)
Unhandled log message: '[Error] Material 'LiberationSans SDF Material (Instance)' with Shader 'TextMeshPro/Mobile/Distance Field' doesn't have a color property '_Color''. Use UnityEngine.TestTools.LogAssert.Expect
UnityEngine.Material:get_color ()
BlockFactoryTests/<CreateLetterBlockTest>d__4:MoveNext () (at Assets/Tests/Runtime/BlockFactoryTests.cs:54)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)
Shader does not have a _Color or _TintColor property.
Material 'LiberationSans SDF Material (Instance)' with Shader 'TextMeshPro/Mobile/Distance Field' doesn't have a color property '_Color'"
I'm 100% sure it's that line too because commenting it out fixes it
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Here is the whole test: https://paste.mod.gg/tqybrtbcsoco/0
A tool for sharing your source code with the world!
hi guys I was trying to do a game about like ship, which is always going forward and you rotate it with A and D. But I dont understand how, I have written a code but it works really strange. Can someone help?
using UnityEngine;
public class ShipController2D : MonoBehaviour
{
public float speed = 5f;
public float rotationSpeed = 100f;
void Update()
{
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.forward * rotationSpeed * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.D))
{
transform.Rotate(-Vector3.forward * rotationSpeed * Time.deltaTime);
}
transform.Translate(Vector2.up * speed * Time.deltaTime);
}
}
if you want to yaw, you would be rotating around the vertical, Vector3.up
here you're rotating around the forward axis, so you're rolling instead of yawing
hmm let me try it
Oh I forgot to say, its 2D game
with Vector3.up it rotates in 3D
ah, it's top-down?
i shouldve noticed the 2D, mb
could you elaborate on how exactly it's behaving strange?
I will send a record in a sec
Do u know how I can unsubscribed a void from an Action only if its subscribed?
no such thing as "a void" here, that's a method
yes sry
Just for info: "void" is the return type of the method
What are you using to subscribe to it?
Unity events?
Action
can you not just.. unsubscribe unconditionally?
yes but it would say that my method isnt subscribed, create an error
Why would you be unsubscribing if it isn't considered to be subscribed? I'm pretty sure we will need some more info
Maybe send the code you have?
{
if (RoomsManager.Instance)
{
RoomsManager.Instance.OnNewRoom += OnNewRoom;
}
else
{
RoomsManager.Instance.OnNewRoom -= OnNewRoom;
}
}
This function is called with this SceneManager.sceneLoaded
I want to subscribe to my RoomsManager when this Instance exists
But unsubsribe it when there no more RoomsManager
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i think this is an x/y problem
step back and consider your design
Never knew this was a thing that actually had a name ๐ญ
here
Seems to be working how the code intends it to work
ok so what's the issue here exactly?
is this the result from holding down w+a?
nah guys i wrote a unit test thats gaslighting me
how's that gaslighting you
that seems.. correct
the color is blue not red but its passing
here is whats wrong
Don't know about that
You set the color to red
maybe that's an issue, but it's not related to the assertion you highlighted lol
Although it says blue
Which may be why
It might think it's red because you set it to red
ok apparently its red but where is the debug that shows it got changed to red
There is none, it was always red
Color color = Color.Red
whenever the color changes its done via the decorator
which means it should always be logged
But it didn't change?
the color variable is red
unless you directly change it, or pass it by ref somewhere, it's not gonna change
i know, that stays the same
Color is a struct, it's passed by value unless specified otherwise
its the particle system material thats meant to change color
and its logging its blue for some reason
add more logs to see when that's happening
for all we know it could be way after the test
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
its a bit of a mess because ive been at it for a while, excuse that
is there a way to find out what render pipeline a compiled/sold unity game uses? steamdb sometimes lists but if not? any file I can look out for etc
Isn't really coding
what a useless answer
try asking in #๐ปโunity-talk
but personally idk
Are you sure you put arrows where that is coming from?
It's saying from the decorator
the debug itself is from the decorator
The material changed to blue, you are checking if red is red
but that's the only thing that should be changing it
so idk how it can end up red and pass the test
i also have no idea why it would be getting set to blue either
Well where the arrows are:
Color color = Color.red;
Assert.AreEqual(color, new Color(1, 0, 0, 1)); (Is red equal to red)
That's that part
Setting to blue may be a different script
The code provided sets the particle color to white
right, but its passing the test after that as well which checks the material
exactly, so how is it ending up red
i want it to, dont get me wrong
but it shouldnt be rn
not if the decorator is saying it changed to blue
I'm not 100% sure about how this type of debugging works so I don't really know persay what I'm doing
wait i figured it out
it still doesnt make 100% of sense to me but i think the debug is somehow from another test
Could be
here is where the blue would come from
Yeah, that would be setting whatever materialB is to color blue
yup
but that introduces even more questions
like where is the decorator debug from the other test
and if its not running how is it turning red
ok
turns out
that im very stupid
and have been looking at the wrong test the entire time
Happens to all of us at some point
Yeah
and no weird voodoo black magic is happening like i thought earlier lol
thanks for the help though!
No problem
this should be in #๐ปโcode-beginner
genuinely what's the difference? I most often just post in code-beginner but partially it may be impostor syndrome
like is there a guide/rule of some sort that helps you tell them apart or?
in General you're generally(lol) expected to know the basics of c#/ unity editor. In this particular case linking a function to an OnClick of a button, those are very basics of unity a beginner question for sure
i didnt see what he posted, just wondering because ive been confused between the 3 channels for a while now
a general question might be.. I am working on this A* pathfinding but the path is a bit to "jagged" How would I smooth out the points so agent moves curved interoplation instead of jagged
ah okay, so its just assumed knowledge mostly
basically
thanks for the clear up
I have a question about lerping. So using something like movement = Vector3.Lerp(movement, targetVel, Time.deltaTime * acceleration); is bad, right. I've seen people saying that you should ground t at a certain point in time like
currentTime += Time.deltaTime;
movement = Vector3.Lerp(movement, targetVel, currentTime / totalDuration);
I really don't understand how to apply this to omnidirectional movement though. When am I supposed to reset currentTime?
https://unity.huh.how/lerp/wrong-lerp
I believe this has some explanations with some alternatives / solution
Applying lerp so that it produces smooth, imperfect movement towards a target value.
I was just on that page. The solution discussed there removes the frame dependence, and suggests a bunch of alternatives like smooth damp.
like the coroutine solution you could potentially reset after the while loop
And when does the while loop end?
when the target value was reached
Use MoveTowards which actually uses the parameters you've passed in the way you expect
yea MoveTowards would be easier to use
Can it be eased, though? The whole point of this is to add weight to the character
bruh what do you mean try it and see, the problem of when to reset currentTime still remains the same
You would need a point of reference from which to start the easing function
MoveTowards takes the current position, the target position, and the speed at which you'd like it to move. time is not a factor here
it takes a distance, not a speed; if you have a speed, you need to multiply by time to give it the distance it wants
this is a replacement for movement = Vector3.Lerp(movement, targetVel, Time.deltaTime * acceleration); where they are passing speed as the last parameter.
and how may I apply an easing function to MoveTowards
oh, i misread targetVel as targetVal and didn't read anything else as velocities, mb
well if you want to apply an easing function to MoveTowards you would ease the speed. or you can use one of the many other available methods that do what you want like SmoothDamp
@astral sky i guess this is probably a safe place to discuss implementing general stuff lmao
Sure
but re: the VPK thing, it's sorta what I'm doing? i took "inspiration" from modding rimworld, which is as easy as overriding XML paths in the mod
no editor required
when I say inspiration I mean "actually this works great, I might as well roll my own version"
Is rimworld slightly like starbound (?) where quite literally everything is defined through a xml?
That's crazy then
like all the items, buildings, etc. are done through XML
The easier your own development pipeline is to develop and add new content the easier it is for third parties to mod it as well
I'm being a bit more aggressive about how freely people can modify things
yep, this is exactly the case
I actually wrote a custom event dispatcher as well (i hate hate HATE C#'s event system and Unity events are too slow, plus I try to detach from Unity's APIs as much as I can)
then I realized I don't really have a ton of use for that event dispatcher in the actual game itself, but hey, at least mods can hook into it
(as an alternative to harmony patching)
I don't remember anything of harmony at all, I know it's used heavily in some unity games but it really depends on communities
harmony's the go-to patcher for rimworld modding, though i think prepatcher is faster
but harmony is a lot easier to use idk
it's also used in Elin but Elin is an extremely strange and niche game
(elin is also a great example of how not to write code. or do content authoring.)
I've never played Elin nor Elin+ so I can't say
tl;dr he does the content for Elin through some kind of weird compiled Excel spreadsheet
it actually hurts my brain
don't do that to your modders LMAO
I've seen plenty of japanese games that do that
Actually I think its explicitly only japanese games i've seen do that for some reason
i think what's weirder is that No Man's Sky has all these archive files that it uses, and then inside the archive files is just
XML
maybe there's more to it but i vaguely remember that from a few years back
because they provide easy structure
it's the archive files that i'm confused about
why go through the extra steps lol
actually
I suppose it'd make sense for load times if you did something like parse all your content defs into memory, then just write those bytes out to a file that can be loaded into memory far more quickly later
why does unity use YAML ? same thing. Provided easy serialization structure / access
you're misunderstanding what i'm saying
I'd say some structured file like XML or JSON is arguably easier to work with than an excel spread sheet
or wait
are you talking about the excel spreadsheet lol
Excel spreadsheets are compact and readable enough, I think they're much more readable than XML/JSON (which are vertical)
some reason people use CSVs they provided structured access / storage of values
okay yeah my bad - I thought you were talking about the XML archive thing at first
granted excel is weird as hell but I've seen it lol
The shitty thing about MS Office files is that they're effectively .zip files, like you can open a .docx file with WinRAR if you want
but that makes parsing them as text really annoying to do
Personally I don't know whenever to serialize my data with JSON or XML or something else, something user readable and small and fast is what I'm looking for
yeah idk I don't think there's anything fundamentally wrong with using a CSV format for content, especially if it's something repetitive as hell
JSON is faster, in general, i don't find it very readable though
Wasn't JSON developed after XML and kinda has taken over XML in a lot of dev?
I'd go with JSON cause its very much used most places and good compatibility / speed
At least stuff like web...
i prefer XML for readability and clarity of what element you're currently in
JSON is generally what's used for stuff like responding to GET requests
It's also used for fast serialization/deserialization for things that you generally won't edit as a player or developer/modder, though ofc people use it for editable stuff as well
XML has limitations on types too iirc , doesnt support arrays structures ?
imo XML > JSON if you intend to edit it strictly through a text editor, at the expense of speed
though for something like a content system, you could maybe hash your game .exe and .XML files on load and store that hash, then precompute all the content you're loading from XML, write the contents of the memory you're using for that to a file, and only re-parse everything if the hash from earlier has changed
which would eliminate re-parsing all your content every time the game loads lol
C#/.NET's built in XML deserializer doesn't handle arrays of arrays
I wrote my own though lmao
It's still fine for reading the files into an XmlDocument, but after that I just handle everything myself
did i miss the harmony talk ๐
I have nightmares from XAML to enjoy XML lol
I think a JSON file would be easier for people to figure out and make stuff like online editors for... whatever reason
currently having a code design crisis in terms of
"okay, I've fired this ConstructionCompleteEvent, and I know I need to recompute navmeshes for this chunk, but do I do that by handling the event, or do I do that by adding the code right after I dispatch that event instead?"
i got a fairly popular modding api using harmony and it was genuinely surprising how little hard limitations there were when you mix assembly injection with assetbundles and/or addressables
I feel like in general best way to support longterm content addition and/or trying to make things not too dreadful for modding is just general code composure thats more event and iterating through collection based to easily allow new stuff to slip in
personally i tend to handle private business before announcing public business for those kinda things
well the idea is that if someone wants to make a mod that automatically levels the structure or repositions adjacent structures to prevent shit like Kenshi Wall Syndrome, the event fires prior to recomputing the navmesh, since all the structures should be repositioned before doing that
but I suppose when I put it that way I should just hardcode in the navmesh change after the event dispatch lmao
"kenshi wall syndrome" being the ubiquitous issue of building walls in games, where if you build them on a slope, they basically end up stair-stepped because each wall is positioned according to where the center of it ends up on the slope lmao
which means you have little triangles of open space under the wall instead
this response is possibly bad for optimization perhaps but i feel like what you do in house shouldn't rely on telling people about it
in my head i would do
construction complete
rebake navmeshes (because it needs to happen in response to construction complete)
tell people it happened (in a "complete" state where the event isn't half finished and for example modders could know the navmesh is updated)
let them update the navmesh if they need to
double rebaking navmesh not great
like at least from reading it the like programming/logic """task"""" of completing construction includes the bake in my head
Working with DOTS just gives me a lot of worries about asset creation / usage and modding, I guess it'd use a lot of factories and APIs like old games
i'm gonna be real with you, my content loader just abuses the ever-loving fuck out of reflection
isn't reflection bad because Unity just keeps it in memory forever?
I mean that does seem like a valid concern ngl
You mean reflection for codegen or something?
At least in the communities i've been in there's a fairly small amount of experienced programmers, I barely know any that have experience in modding and DOTs (they do exist im sure but gets pretty rare)
i'm not sure what you mean when you say working with DOTS I guess
that feels like a super broad term
unless it means something specific here and I missed the memo
In terms of an outside modder trying to manipulate and extend a unity game built using a lot of DOTs
can I get like a concrete example
wait
like a scriptableobject? lmao
honestly if you want to make your game as moddable as possible you're better off treating Unity as a renderer (and level design tool if necessary)
no as in like ecs/burst/job shit
ah that
not sure how a modder wouldn't be familiar with ECS if they're modding unity games tbh
burst/jobs are a different beast
I don't personally know any modder who is familiar with ECS, You'd be suprised
I myself have no experience with it
I think the moddability of a DOTS / ECS project depends on the asset pipeline, because if everything is already pre-baked and nothing can be added at runtime that's... yeah
Same, we also don't support modding here afaik
Unless you're talking about making a moddable game
...are we talking about the same ECS? the idea of an entity component system?
DOTS is an ECS
If staff pokes us for being a little close to the line im happy to chill but i don't think we're talking anything to bad rn
or is there just a completely different set of acronyms here
i'm talking about making moddable games at least
the idea of the entity component system, Unity's one
p sure the others are too
My experience is from modding other peoples games but ๐ค
oh. unity's ECS is pretty straightforward though? i feel like anyone who knows enough about programming would be able to work it out
i worked in AAA game dev instead, which was objectively messier
and more complicated
I think respectfully you might have an overexaggeration of the programmers who get involved in some games modding communities ๐
actually fair
when i was like 18 i tutored this guy a couple years younger than me in Java and after a bit it turned out he'd just been pasting code snippets from google instead of trying to understand anything I was telling him
and one time he sent me a code snippet where he pasted an entire method, declaration and all, into another method and could not figure out why it was causing an error
Only reason my modding stuff has blown up is because it lets people make mods without programming at all lol
I've also seen some genuinely questionable code when decompiling other mods
A lot of DOTS involve baking and blobs baking, which the point of it is offering fast, precompiled content, so....
It's really not. A lot of people are waiting for the 1.0 release because it keeps changing and is very confusing
You'd have to do that stuff at runtime, unsure how bad that would be
Entities 1.0 released a lot of time ago
I don't think DOTS is 1.0 though, just parts of it? Or did I miss that
also man this is headache inducing
A lot of people I know use LeoPotam's ECSLite. Very easy to get into
so far my only Unity villains as a modder have been
-tags
-layers
-not being able to load a scene, touch its stuff before it gets awake/onenable calls and then unload it
-enums !!!
the last one isn't Unity specific but still
i'm trying to work out something for tags/layers myself right now lmao
what's up with enums?
not easily extendable
ah
back when I made minecraft server mods I got around this by using data classes instead
there was a lot of passing strings around with that one
right now i use scriptableobjects in place of enums and physics materials in place of tags
I really don't know how to make items / buffs / damage types without an enum
but it got to the point where it was all content system driven so it's not as if I ever had to manually go "GetDamageType("physical")" or anything like that
And how to go around them, I'm no way in hell doing a dictionary with a string lookup, enums are just way better
Use scriptable objects as identifiers instead of enums, you get a lot of extra stuff with it too like UI sprites, descriptions, etc
Just be sure to never store state in a SO
dictionary with string lookup is completely fine if you're configuring all the damage types yourself anyway
i either iterate through lists of scriptableobjects or explicit references to them
the main issue with it is if you're hardcoding some shit into your game, at which point it becomes a problem
A catalogue or something? I'm trying to get really away from catalogues to not have catalogues because
Nobody likes a 30 second long boot up time...
i have no idea what a catalogue is
Which I am aware is a major issue in some games
my rimworld install takes 20 minutes to load
Dictionary, basically, where everything is stored
You CAN have a catalog of them sure, but no need. Instead of a damagetype enum, for example, you just stuff a SO in there
i would not use scriptableobjects if you want people to make mods that don't require creating an editor project
unless SOs can easily be edited outside of the editor now
Maybe deserialize them from jsons?
SOs are just YAML but... you aren't going to define them without a interface, unlike JSON or XML
serialization/deserialization are the main answer to this
i mean they have always been to an extent
oh, last time I used them they were a pain, but that was years ago lmao
i don't think it's that big of a deal
but back then I was using them As Intendedโข๏ธ so it wasn't an issue
My game uses a lot of scriptable objects instead of enums. I use them for my damage types including damage type mitigation. Works extremely well
not a Unity game but I did something similar for a minecraft mod I made some years back, except it's YAML instead
How would you access them type-safe in code though?
type safety is an illusion
If you're modding maybe
I'd maybe refrain from having the description manually created for that if you're not working alone lol
I can't just use strings in burst, data has to be non-managed
Like, the damage types and buffs have to be either unmanaged data or prebaked blobs
i'm not super familiar with burst tbh, i'm using it for world gen on my end but i don't know the full extent of what it does
This is designer friendly
idk if you've played warframe but they did a pretty major overhaul of damage types a while ago and if you did something similar there, there's just a risk of someone modifying the "armor" entries without updating the description to reflect the changes is all
I do not give a shit about someone hacking and modding my game
that is not what I was referring to but alright
which is why I said if you're not working alone :p
if you're working alone and trust yourself to maintain those descriptions, go for it
Right but why are you doing this in burst
Oh I see what you mean, yeah it's a pain to update all this UI info alone yeah
parallelism goes brrr
but why do you need to do that in parallel
I have no idea how compatible regular C# threading is with Unity actually
I've played modded RoR2 and its honestly god awful with mods and its all because of everything going through the main thread and garbage collection
strings are just char arrays btw, and chars are just bytes (or shorts depending on character set)
I mean I guess I can do that because Burst has FixedString128Bytes and similar
I've never modded RoR2 (played it but never made mods)
yeah same
however I'm willing to bet that part of it's just people using bepinex and writing dogshit code lol
But the catalogue problem I mentioned earlier? If you have like 10 RoR2 mods the initial game load goes from 1 minute to... 6 or even 7
A big problem I've noticed with certain games is also that the developers think they're clever and implement like...a mini ECS - Rimworld is super guilty of this - and then it performs like total shit
it's REALLY bad
People can write good code with bepinex ๐ฆ
i have never had this happen, wtf kind of mods are you using
oh thats probably just assetbundle and/or addressable loading
I have a skyrim modlist with 1100 mods that loads in like 30 seconds
What I like from RimWorld is iirc the fact that their mods load at runtime and the mod menu where you can just enable / disable workshop items, and you don't have to reboot the game
Yeah. Use a mod manager lmao
this should probably be a thread at this point tbh..
might discourage someone posting a Q
fair, I usually try to avoid threads because they hide shit from people coming in who might want to contribute to the conversation
bepinex modding has a massive problem with asset modding because people do it non coroutine or async so because bepinex loads up each plugin one by one the entire upcoming modlist has to wait for the previous mod to finish loading their bundles before the next mod in the line can even start
lethal company can hit like 5-10min cuz of silly modders doing that kinda shit
but you're also correct that someone might not wanna post a question mid conversation
true but also this veering offtopic too
yeah this is what I was getting at
Maybe something like "flexible easy asset authoring" or something...
which brings me back to why I wanted to write a moddable game in the first place
to minimize the risk of people accidentally creating huge load times lmao
Unity DOTS has its own Asset pipeline that doesn't use neither Assetbundles or Addressables, very scary!
i'm working on a game that's kind of a mashup of rimworld/kenshi/borderlands and i can 100% see that kind of thing having a modding scene
not that I'm deluding myself into thinking it'll be the next big thing, but it can't hurt to make my own game easier to add content to, for my own sake at least
Apparently it just bundles everything automatically if they are referenced in any scene, so you don't really get a saying into what goes or doesn't where or any kind of organization at all. It really makes me worry about future content delivery because with standard Unity you can just ship a new asset bundle or addressable in an entirely new "folder" and be done with it...
unity's hitting the AAA problem at this point where there are like 3 systems for something and none of them know what the others are doing
at least that's what this sounds like to me
We had a big problem at my last job where we had multiple systems competing for GPU memory with 0 information shared between them so
I really hoped that Unity 6 would be a soft-reset and they said that they aren't doing it that and will keep everything legacy and.. yeah
Like please, just get rid of the old input system
leaving it in is fine imo, considering you can disable it through the editor
okay why are dealing with canvas/panels/ UI so complicated xD.
what you see is NOT what you get... >.<
old or new UI?
im just using the regular one..? not sure about whats old or not as im new to Unity
Also holy shit it's the nosam cutter from warframe (that was a joke please do not crucify me)
LMFAO
UI Toolkit is the newer UI system
uGUI (Unity GUI) is the one you can add easily through the editor by right clicking and adding a Canvas, Text, etc.
ohh so i should probably look into this UI toolkit thing
I'm not familiar with UI toolkit myself but it sounds like the older one
oh wait
they have different use cases
UI Toolkit is good for UI-driven applications from what I'm seeing
UI Toolkit is HTML + CSS, it doesn't support custom shaders if you're looking for that
I'm actually unsure about UI Toolkit's performance when compared to uGui, I think it's better??
UI perf has honestly never been something I've considered
Only time I ever ran into an issue with UI performance was using ImGui at work and accidentally loading 42 GB worth of data into a window
I was writing an asset browser
Well i have a half working debug console that I made but the UI is fucked (but it gets the job done, since i can just copy the logs) and i also want to create an inventory UI (the system works, the items just save in backend and cant be displayed yet)
Maybe looking into this UI Toolkit would be good for those as they only need to be simple
LMAO nice
For an inventory you might wanna consider Unity GUI
I'm biased though
Big thing with unity GUI is easier script references for individual components
thats what ive been trying to do but its hurting my brain because in scene view it looks great/game view, but actually IN GAME its a mess and NOT what i get lol
ill give an example one sec ill send ss
resolution issue maybe?
wait i wont send a SS actually cuz i deleted it all in rage
sounds like you might wanna check up on your anchor/pivot
but you get the point lol
i will double check when i re do it
so, should all my UI elements be on one canvas ?
absolutely not
I had a bit of a "what the FUCK" moment when I was first implementing my UI code and I wasn't sure why Unity needed a Vector2 for anchor x/y instead of just one vector2 containing the relative x/y of the anchor point
Any changes in a Canvas makes that canvas dirty, and it will be redrawn
yep
ooooo okay
I mean for like a HUD you can use one canvas
You can, however, make different canvases for different elements, I think it'd be fine then
But I'd use a separate one for stuff like in-world elements
you'd need a separate canvas per in-world element, to be clear, not one for all of them
What I've seen some games do is have one giant canvas that just covers the entire screen and then inside they draw things, kinda like flexboxes
im gonna add an inventory button like this. shoudl this be on the same canvas as the roll button then ? but have a child canvas inside the main one or something?
you thinking of something like rendering to a rendertarget?
No, something like a Canvas that is like a "safe zone" and then everything is positioned relative to the Canvas, instead of the screen or camera or w/e
you can slap the button in there
nobody will stop you don't worry
Yeah just don't put too many elements into one canvas
hmm, that sounds weird
well more like - what does that offer for something like a HUD lmao
Well you can disable the entire hud by hiding the root canvas that's for one
and if you want to make splitscreen or something similar you resize the canvas' size to half and everything inside resizes accordingly
UI's are confusing in unity >.<
i have a canvas node and then it has child nodes for the HUD elements
UI is confusing no matter what you're doing honestly
There's always some aspect of every UI framework that just makes me want to cry
should i not even be using a panel here tbh
i mean its just a button
idk
i could put all the buttons as childs of the canvas , would that be better?
and only use panels for like.. .the actual inventory or whatever i need?
no idea what a good workflow is for this
or i could jsut try everything until i get it ;p
I mean if you right click and just add a button without having an existing canvas, it'll generate a canvas with the button as a child of that canvas
and the text as a child of the button
i mean in reference to the panel mostly
I have never in my life used a panel if I'm honest
i guess for this i dont need it
but also I don't do much UI stuff in Unity
if it's similar to a WPF pane, though, it'd make more sense
derstijkougejrsigdrsijodsrgjiogdsriojdsgorijidjsogrpijodsgprijodsgrijosdgrijosdgr
thats my ted talk, thanks
a panel will be good when i need to list/display inventory items
okay yeah a panel is apparently just a shortcut to creating a UI gameobject with a recttransform, image component and canvas renderer
but maybe not so much for just a button that rolls ๐
you do not need one to add a button to your canvas
okay actually that part about reflection cacheing might be a clue as to why Rimworld runs more slowly just from adding mods ๐
but now I'm stuck on "how do I handle object def classes added by mods"
I read about how there was a whole drama about the reflection caching in one community
funnily enough
Because a lot of users kept complaining about performance?
I really don't know how to go around it other than factory methods or just any kind of system with a static method where everything goes through
i might be wording this completely wrong but is there a way i could get a vector 2 from a number of degrees ex: getting 1, 0 from 90 degrees (im sure thats not right, just an example of what im trying to accomplish)
you can use Vector2.Angle(a, b) and Vector2.SignedAngle(a, b) where you define an arbitrary vector a to represent your zero-angle directions and compare it with any other direction b. https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector2.Angle.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector2.SignedAngle.html
LONG STORY SHORT, it looks like everything shoudl be working
but its not
its not a code issue, the logs show and work and are available, and confirmed because im able to copy them. but i cannot see them. as you can see in the screenshot though, i (hopefully) have it positioned and everything correctly
its instancing the prefab for the log entries
yo im trying to make dark fantasy game. and i need help. im new and i wanna make small but great game so if yall can help dm me
its not a code issue
well this is a code channel. but it sounds like it might be a code issue, can you actually show the code
whats the proper way to link code here without server getting mad at me, iirc i cant just post it directly
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
i also linked a screenshot of the reference fields
and is this issue only happening in a build, or does it happen in the editor as well?
haven't even bothered checking in editor, let me do that rael quick
yeah, in both
i would think it has something to do with the prefab
im just not sure.. what ๐
and you're certain there are no relevant errors in the console
or any errors at all for that matter
yeah thats all good
not sure if it helps mch but this is my full heriarchy
then the text goes child of content
do you actually see the text objects being added in the hierarchy?
this is not a place to get handouts. go !learn and make it yourself
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
๐ญ ok
yes ๐
so its definitely like, working
show the inspector for one of the objects that gets added at runtime
ok ok
those logs are exactly as should
all of them
so the text works too
๐
which is all good news
well it's currently disabled, you need to look at it while it is enabled
LMFAO
idk why i did that
welpo
the position
is
-1xxxxx
well
i guess thats just the scrolling nvm
thats fine
bro if yall have normal movement js dm me. these learning thing is laggy asf . cant even hear what hes saying
do you know C#
yeah
#archived-code-general message
no one is gonna dm you to give you free code
i no longer see it highlighted in the scene, if you scroll up do you see anything?
yeah i see what you mean. let me look into that
bro free??? if u want money go get job
you understand that paying for somebodies time to produce something for you, is an incredibly normal thing, right
start by learning lol, instead of demanding people write your code for you
if he has code and uses why dont help me out and give it to me? is just helping
your scrollview bar is incredibly tiny also, meaning theres a lot to scroll
if u want money just say it im gonna give u 0.50$ for ur meal today
looks like the prefab (for the text) is vertical, too
what obligation does anyone have to give you their work
either put the work in yourself or go find some other server where they allow children to beg for other people's work
you said you know C#. If you cant put together if (key is pressed) {transform.forward + 1 * dt} blah blah blah then idk if any of us can help u
im just asking . if someone is kind they will. they dont have to work more and more for it.they created smth for themselves and just pressed ctrl c and ctrl v to help others
no i dont know coding
stop spamming the channel please, look at the #854851968446365696 on how to ask questions when you actually go learn properly and have real questions. You spent 5 minutes on unity learn before coming back and asking the same question for someone to write the code for you
why learn to be a programmer, if you just want to take shortcuts and that save you programming
you 100% are trolling
bruh . i didnt meant im the fing pro at it
i mean, tbf a lot of programming is taking shortcuts to write fewer lines of code lmao. but yeah this kid is on something else
how do i learn? i dont have the starting point
i need starting point to learn
i cant create things from air
from whereeeeeeeee
how about we just get a <@&502884371011731486> to come sort this out. got some slurs in that profile anyway so they might as well just clean this up entirely
wow
kids these days sheesh
i jsut asked for help and im getting jumped
Learn C# basics in 1 hour! โก This beginner-friendly tutorial gets you coding fast. No experience needed.
โค๏ธ Join this channel to get access to perks:
https://www.youtube.com/channel/UCWv7vMbMWH4-V0ZXdmDpPBA/join
๐ Ready to master C#?
- Check out my full course: https://mosh.link/csharp-course
- Subscribe for more awesome content: http...
ty this server and there comunity
see. this is what i wanted
nothing more
done
they were also linked the unity learn site three times. plus the pins for intro to c# are in #๐ปโcode-beginner
when i was your age we didnt have youtube tutorials to learn. you just beat your head against brick walls until shit worked you know
๐ Get the Premium Course! https://cmonkey.co/csharpcompletecourse
๐ฌ Learn by doing the Interactive Exercises and everything else in the companion project!
โค๏ธ Watch my FREE Complete Courses https://www.youtube.com/watch?v=oZCbmB6opxY
๐ฎ Play my Steam game! https://cmonkey.co/dinkyguardians
๐ Get my Complete Courses! โ
https://un...
clean? im not some kind of shi@ like u to clean
demanding people just hand you their code instead of putting in the effort to learn when resources have been provided to you multiple times is not "asking for help" it's "asking for handouts because you are lazy"
demanding?????? i asked if they could help me out
or you bought those giant ANSI C encyclopaedias
and now we're at the ad hominem lmao
and you figured it out
i know what c# is but dont know how to use it
ok ok
im not lazy im new
then get to learning
you have to understand , programming is not writing code. its PROBLEM SOLVING. and you are refusing to solve a problem
whereeeeeeeeee
game development isnt really the first thing you should be trying
you understand having people do it for you you'll still understand none of it and wont get anywhere
you were linked 6 different resources now.
then what should i try. i asked where to start and i got jumped
hey now you can start with CLI games!
velocity = Vector3.SmoothDamp(velocity, direction * speed, ref velocityRef, smoothing);
cc.Move(velocity);```
I'm so confused. This should be frame independent, right? Why is my speed changing with the game's time scale?
thats a good idea, though actually
1 and that is worst thing
is it under the Update() function
Yes
game dev is p[robably the best way to learn code
thats how i've been doing it. although i am good at basics i think, im falling into a pit of using chatgpt too much and letting him solve my problems LMFAO
youd have to show what most of these variables are. We dont see what direction, speed, smoothing is.
https://en.wikipedia.org/wiki/Fizz_buzz make this
Fizz buzz is a group word game for children to teach them about division. Players take turns to count incrementally, replacing any number divisible by three with the word "fizz", and any number divisible by five with the word "buzz", and any number divisible by both three and five with the word "fizzbuzz".
it wont be ghost of tsushima but you gotta start with the fundamentals and CLI code will get you very deep into understanding OOP
gpt just makes more mess than i could just do it myself most of the time. although i have to admit it's understanding of the xNode library was a godsend since they didn't really document it very thoroughly or keep it up to date
wtf is that :0
Also theres no off topic in the channel, the conversation you all are having isn't related to helping anyone and the person clearly wasn't even reading half the messages since they were linked 6 times for resources and only saw 1.
gpt found me all kinds of stuff i didnt know about xNode
and the official discord is dead lol
Well would that really change anything? Smoothing is 0.3f, direction is the input direction, speed is the walk speed (0.01f)
its a great assistant but i wouldn't use it for the whole project
Multiply what by deltatime
of course itd change something. all youve shown is a method call and 3 unknown variables. We dont know what those variables are, you could be assigning completely random values for all we know
The question regards why it changes with time scale. I thought SmoothDamp was frame independent, the docs show that it uses Time.deltaTime by default.
this is how mine works @mossy flare
