#archived-code-general
1 messages · Page 421 of 1
better yet - just add the Rigidbody directly on the prefab instead of adding it in code.
Also makes sense, let me change those real quick
Vector3 offset = new Vector3(this.transform.position.x -0.5f, this.transform.position.y, this.transform.position.z);
GameObject bulletInstance = Instantiate(lrSpecialBullet, offset, Quaternion.identity);
I added an offset vector and changed the instantiate line to this, but now the projectile never instantaites at all for some reason
Maybe place a log and see if those lines were executed
The lines were executed, I did check that. It's likely im just using instantaite wrong, i'm just not sure what the issue is
It wouldn't instantiate the object if the lines aren't called. Other than that, the object would be missing from the hierarchy if the object was destroyed.
it will spawn. Just not in a visible position probably
Yeah, the code runs but there is no object in the hierarchy
again have you actually checked what offset is defined in the prefab itself?
it's possibly getting destroyed right away
you probably have code that destroys it when it collides with something
Oh yeah i do, let me actually stop that rq
Also, you were correct there was an offset in the prefab
set it to 0
As a general rule of thumb prefab roots should always have 0,0,0 transform
Yeah, that makes sense
Still, the right works and the left does not, even turning off the destroy code
In what way does it not work
One second
Can you show the console logs?
And the edited code
surely if the prefab root was set as 1,1,1 and you instantiate that prefab at 0,0,0, then the position the instanced clone would be at is 0,0,0
I think the middle of the prefab is instantiated at 0,0,0, but the projectile was offset from the center of the prefab
But with the form of Instantiate being used, it will be at 1,1,1
He's not using an Instantiate form that sets the position
that is also a problem
it does sound right for it to be instanced in whatever the roots position was, say I had a cloud prefab that I want to be at 0,100,0, I could simply instance it at 0,0,0 and I know the cloud will actually be spawned at 0,100,0
any help would be great! :) i have an issue where keep getting the error that the object reference it not set to an instance of an object and im not too sure where im going wrong, public class Weapon : MonoBehaviour
{
private InputManager controls;
private Camera cam;
private RaycastHit rayHit;
[SerializeField] private float bulletRange;
private bool isShooting;
private void Awake()
{
controls = GetComponent<InputManager>(); // im getting the error code here when i run the game but im not entirely sure whats causing it
cam = Camera.main;
controls.onFoot.Shoot.started += ctx => StartShot();
}
That line cannot be causing that error
show the actual full error message
!code
Also what line
📃 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.
and the full script(s)
So i figured it out
I just had to increase the offset
Thanks for the help, sorry for making that more trouble thatn it needed to be
its because GetComponent simply attempts to get the component, so its likely that the component doesnt exist. so later when something tries to use controls.something they cant do that, as the original InputManager component was never found
Okay, now what is line 19
controls.onFoot.Shoot.started += ctx => StartShot();
the only line in Awake that could throw is the last one
so it's controls that is null then
thats line 19
So, something on that line is null but you're trying to use it anyway
and this means that controls is likely null because there is no InputManager component attached
you never initialize your controls
nvm InputManager seems to be component not input c# class
or one of the fields in that chain is null
Actually it may be more likely to be that - and probably a race condition with the different Awake functions
So either controls, controls.onFoot, or controls.onFoot.Shoot is null
whatever game object has the component thats giving the errror, does not also have the InputManager component attached
controls = GetComponent<InputManager>();
Debug.Log(controls);```if the log produces an error, thats a very straight forward problem
that log wouldn't produce an error either. but it could print null
You wouldn't get an error for that
thats the full script
oooh right of course
NRE only occurs if you're attempting to access a member from a null reference
to be fair im in the middle of cooking so its hard to think 😅
It doesn't manke sense that we're doing new InputManager() in one script and GetComponent<InputManager> in another
something is wrong
this confusing af
i tried a different method but ended up with the same error the one i posted is the original one i was working on my bad
lets see what InputManager is ?
nest keeps getting worse
is PlayerInput your class or the unity PlayerInput ?
mama cried but it wasn't onions
unity player input
well its a component you should not be new it
can you show it , just incase
A picture would suffice since it isn't a script
PlayerInput doesn't have type safety no? you wouldn't be able to see any of the actions without string
could be classic mistake of naming something the same as unity component
My Unity has to Reload Domain every time i change some code. Is there a way to only make it compile when i press play?
I think you can only switch to manual?
and that would be for all assets
it's likely that they followed one of the many tutorials that tell you to create an input action asset named PlayerInput and they didn't realize that selecting the Generate C# Class actually creates a class called that
thats the input system action map, unless you want the generated script?
note that reloading domain and compiling are two separate things
so you did generate a script from this ?
and called it playerInput ?
this issue is stemming from tutorials that werent lining up
ok so new() would be correct..
the name is just bad cause confuses with unity Component PlayerInput (also horrible name)
it was auto generated from the playerinput actions map so there is a script named playerinput
yes so when you do new() your actions, you also need to .Enable() them
well yes, following random disjointed tutorials is going to cause confusion if you don't know wtf you're doing.
i'd suggest stopping what you are doing and go through the pathways on the unity !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
they are in OnEnable and OnDisable, those methods just happen to be at the bottom of the class
that is calling GetComponent for the InputManager component
which is the component that instantiates the PlayerInput object
their WeaponManager component is erroneously instantiating InputManager though when it should be using GetComponent
OH thats InputManager
myb mb
this is mixing 2 different inputs ways lol confused me
serializefield variable vs getcomponent in start, which is more optimized? and WHY!
serializefield variable ofcourse
dependency injected vs runtime lookup
have a start with 7-8 GetComponents x 100 enemies, see how efficient that is for Start to run
You want to look up content size fitters - unfortunately the solution isn't super trivial, but it's not impossible. Basically you need to know that content size fitters will fit content after the current tick - so if you're trying to get the rect transform size, you'll need to wait a tick until the CSF and layout group have had a tick to repaint themselves
thx for the response, I did somehow get it to work...
It was not intuitive at all but I believe what happened was that when I put content size fitter on the very outermost element the content size fitter magic trickles down to the individual child, so I just made my textbox prefab as if it had a content size fitter and then it seemed to work
I wrote some code a couple years ago that will do something else you might find useful - sets a GO to the "minimum" size based on the nested content - useful if you have nested CSFs like that.. lemme see if I can dig it up and paste it.. No idea what state it's in but you might look over it and find something useful
This code is at least a year old - but I think most of my codebases still use this to set things vertically to the smallest amount.. just be careful since it won't work for disabled GOs (the CSFs don't do anything while disabled) or not yet Awake'd - ie, you can't do it in the same tick as when you instantiate - hence the wait one tick coroutine at the top
ty
I am stunned that such a thing is not built in behaviour for the layout groups
Though, I cant speak for the new UI system
The way they currently work, you know all theyre doing is just divide the length by number of rows/cols + padding
majority of use cases this is enough, so its not too much of an issue
how do i extend customEditor to make it work above an item (such as [Textfield("EditorText")] above a string). Like how you use [HideInInspector]
🤔
thank you osmal, i didnt think of propertyAttributes
I've also wondered about this, but hadnt looked into it before now. https://github.com/dbrizov/NaughtyAttributes I poked around in here to see how they implemented their [button] attribute, and I noticed that derives from Attribute not PropertyAttribute, yet other classes use the latter
I cant seem to spot the source for Attribute in that repo, or in the docs
Attribute is a built in C# thing
ah!
thats interesting to know! thanks
Correct.
The content size fitter resizes its own RectTransform based on how much space it wants
You should not have content size fitters on an object with a layout group in a parent
more specifically, you shouldn't have a fitter controlling a direction if the parent has a layout group controlling the same direction
Doing this is objectively wrong, and it results in all of this weird hackery
If your parent controls your size, then your parent will give you enough space -- as long as you ask for it
looking for some clarity on some stuff since there's a lot of mixed info online.
does anyone have resources/hints on what I should be using to mix the following:
- unity UI (w/ canvas and so on)
- mouse events on gameobjects, but not through the UI
- the new input system
so far I've seen posts/articles/etc. that either ignore interaction between one or more of these, claim certain approaches are more or less deprecated, claim some are poorly (or barely) supported by Unity in some unfinished state, etc.
just kinda baffling that something so simple doesn't really seem to have a straightforward approach, at least that I've found so far, so any nudges in the right direction would be appreciated lmao
So this is something I only figured out like
a week ago
the Event System is, by default, only used to interact with graphics
via the Graphic Raycaster
however, you can use it for things with colliders too
using the Physics Raycaster
So you can add event handlers to game objects with colliders, and they'll only receive click events if the UI isn't in the way
I believe you just need to slap a Physics Raycaster onto the object with the camera
Most UI events also sort on hierarchy for when that raycast is blocked, so you will always be blocked by the most priority
otherwise manual graphic raycasting is basically a raycastall
Makes sense though, how do you know what's being blocked if everything is occupying the same z space?
yes, UI uses different rules
the revelation I had was that the EventSystem could be used to click on colliders
it's one big unified system
I've been using EventSystem.IsPointerOverGameObject() to check if my cursor is on top of UI before doing a physics raycast to look for an object
I thought that's how it would work, but it doesn't appear to be. idk. atm I've just got a simple OnMouseOver on an object with a collider, but the input passes directly through UI elements.
That has nothing to do with the event system
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.OnMouseOver.html
All of these methods don't care about the Event System at all.
I'm also pretty sure they only work with the old input manager, but I have not tested that.
yeah that's kinda my issue lmfao, it seems like nothing is designed to work with other parts of the engine on a fundamental level
so I'll need to instead set up manual raycasts and handle the events from that within the camera, then?
No.
you add a Physics Raycaster to the main camera, then add components that implement the various event methods to the target objects
When you click, the Event System will test for both UI and non-UI objects
it'll hit Graphics (in your UI) and Colliders (elsewhere)
hey this is my first time using unity for an assignment and my player object is supposed to collect the coin but instead it's just phasing through all of the coins even though the colliders are there. Does anyone know what the issue may be. (first ss is the for the coin object thats supposed to be collected/destroyed, the last two are for the player object)
that interface is useful, that part makes sense. is the raycast component set up to automatically handle mouse input fully for interacting with those, or do I have to actually direct a destination vector to screenspace and whatnot on my own?
The Event System does all of the work.
you don't shoot raycasts at the UI, do you? (:
I mean, no, but I also wouldn't expect it to be considered a raycast in the first place I guess - or that if it is, that while parented to a camera that it wouldn't like... default to just extending toward the camera's facing angle, without the destination point moving with the mouse. kinda a bit of a misnomer on their part imo since it's more of a mouse input handler built on top of a raycast component.
but uh... upon testing, it seems it doesn't work. could be I missed a step - currently have the Physics Raycaster on my camera, the object (with collider) implements the necessary interfaces, but no input captured. UI still works though- oh wait. would the canvas prevent input from being passed behind?
if that's the case I assume I'll have to mask that in the raycast but idk if there's a better approach
hm, worked fine for me when I just tried it out (in a random vrchat project..)
However, if anything in your UI is blocking the raycast, it won't reach the object
This could include non-visible objects
turns out it wasn't the canvas after all, I removed it completely and still no input captured on the gameobjects
You do have an Event System in the scene, right?
yup!
and the Physics Raycaster is attached to an object with a Camera component (not a Cinemachine Camera, perhaps)
yeah, just a default camera object from a brand new project scene
when you say "implements the necessary interfaces", do you mean you attached a component that implements, say, IPointerClickHandler?
that's what I used
yeah, in my case I used IPointerEnterHandler and IPointerExitHandler, but I would assume they work as you'd expect
If you turn your UI back on, can you click on buttons?
yeah.
so your scene currently contains:
- a cube (or some similar object), with:
- a collider
- your component
- a canvas (deactivated)
- an event system
yup, precisely that. and the camera with the physics raycaster.
the collider is a 2D (circle) but I wouldn't imagine that would make a difference, since it worked with the previous methods
(e.g. OnMouseEnter)
Are you using Trigger events? You may need a rigidbody on the character, but you can set it as kinematic.
...wild. any complications from adding both the 2D and the normal one, in case I want to interact with both?
Not that I'm aware of
aight. thanks
But I also haven't used them much before
yeah that worked. hopefully nothing explodes! thanks for the help.
if I have a scriptable object that has a [Serializable] object instance as a field, can I straight up use it and modify it, or should I make a copy first?
Why wouldn't you be able to use and modify it
It will get modified on the asset in the editor though
If that's what you mean
If you dont want to modify the base make sure you either have a value type or copy it beforehand
if (Input.GetKeyDown(KeyCode.E))
{
RaycastHit2D hit = Physics2D.Raycast(
origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
direction: Vector2.zero,
distance: Mathf.Infinity
);
if (hit.collider != null)
{
rope.enabled = true;
grapplepoint = hit.point;
grapplepoint.z = 0;
joint.connectedAnchor = grapplepoint;
joint.enabled = true;
joint.distance = grapplelength;
rope.SetPosition(0, grapplepoint);
rope.SetPosition(1, transform.position);
}
}
if (Input.GetKeyUp(KeyCode.E))
{
rope.enabled = false;
joint.enabled = false;
}
if (rope.enabled == true)
{
rope.SetPosition(1, transform.position);
}
this code is designed for a grappling hook but when it runs the player loses all momentum at the bottom and barely moves whatsoever, can someone help?
• your raycast code doesn't go from the player to the spot that you're clicking
• nowhere in your code does it change your player's position/velocity
shouldn't it preserve the velocity though? and how would i fix the raycast
RaycastHit2D hit = Physics2D.Raycast(
origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
direction: Vector2.zero,
distance: Mathf.Infinity
);```
If you want to do a mouse raycast in a single point to 2d objects, you shoould be using https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics2D.GetRayIntersection.html. with Camera.ScreenPointToRay
he also like stops being affected by gravity when basically horizontal
is a layermask required btw
not really, but depending on the function's override they might make you use it
Only if you want to filter the raycast results by layers.
so the frog basically starts moving really really slowly along the circumference of the circle that would be traced out by the distancejoint at around this point
would switching to rayintersections and camera screepoint to ray fix taht
when i modify scriptableobject data during runtime, the changes save - is this the correct approach to fix the issue or will i run into bigger problems down the line cause of it?
That is fine. Though generally it's easiest to treat SOs as immutable and to create a runtime instance of the data that's modified
hello i started to learn programming in unity and once i learned the basics i dont know what to type in the programming scirpt i have ideas but i dont know how to type you know theres errors and stuff.
Is there a question here?
yes
Could you try to rephrase it? Because I didn't see a question in there.
i learnt the basics like variables function
but i dont know what to do once i start to program my self
to be frank: you haven't learned the basics, then
it's common for people to over-estimate how much they understand when they're starting out
I heard this quite a bit from students when TAing
I also still don't really see a question here
nothing wrong with being a novice -- you just need some more time (:
but yeah it's going to take you at least a year before you comfortably "know the basics" of programming
oh ok thanks 👍
and you really just have to do more
the Unity Learn pathways have a lot of material to go through
its alright
repetition will get you more familiar with this stuff
do you have any tips or courses that you think will benefits me
The stuff here is good https://dotnet.microsoft.com/en-us/learn/csharp
So I want my player to not fall though platforms that are moving fast which, of all things, seems like something kinda simple, but...I'm just not exactly sure what a reliable solution would be for that. I'm using a raycast to check if the player is on the ground btw
What are you using for physics?
A simple raycast downwards and teleporting using Transform?
If you're using Rigidbody, try setting the simulation to continuous
oh yeah..I guess I didn't really make it so that the player actually sticks to the platform..
I only made it so they can jump if they were on ground
yeah that or use physics to do collision
and then...there's also horizontal platforms... Guess I'll just do that when it becomes an actual problem
what are you using for movement?
you could probably just have platforms move stuff on top of them with movetowards
or maybe set a friction
or maybe parent them
there's a lot of ways
If you do not want to parent the object, consider using a parent constraint component.
Really wish some of the constraint stuff were just gameobject properties
lot of times I just want to child something and prevent rotation
Position constraint?
yeah im saying feels bloated to do that
like near the transform values should just give us constraints
I mean... is it possible to extended the Transform class?
yeah, like RectTransform
idk if you can like, replace the transform of an existing game object though
All my homies forgetting scale
I'm generating a level at the start of a scene. Should this be done with a coroutine instead? The first frame of the scene can take a long time. Is using a coroutine faster? Is it bad practice to overload the CPU with a long Start function? I'm assuming yes. Maybe this is a dumb question.
Use the profiler to determine the limiting factors and try to decouple whatever isn't necessary for the main thread. For instance, math or other non-Unity data could be done with tasks or over time with a coroutine.
it's all about the player experience really, freezing on a pretty loading screen that says "please wait" is a lot nicer than freezing on a black screen or with half the HUD loaded in
but using a coroutine lets you do stuff like show a progress spinner, so if it's a really long load maybe you need that
holy f bros. I did not realize you could use yield return in a for loops like this
this is what the constraint components are for!
cus it would shit on performance to have alternate processing for transformations
maybe my question is more suited here, how does one DRAW a mesh from a matrix of chunks efficiently, the generation is no issue but the second i have to render it takes very long to make the mesh due to checking through every block to see if their is neighbors touching. so how do i go about it?
Sorry but I'm struggling to understand what you are asking exactly. When rendering a mesh, you wouldn't need to do any extra processing. When you generate the mesh, you would exclude every part that's not visible already so you would only need to render the mesh as is later. Is this at all what you mean?
like what? super curious 🤤
I didn't know you could have yield return in a for loop in general! 😮
{
bool isSpawned = false;
while (isSpawned == false)
{
Vector3 randomPos = RandomPointInBounds(pos, maxPos);
if (SpawnLargePrefabRandomly(GenerationManager.instance.GetRandomBuilding(), randomPos))
{
yield return new WaitForFixedUpdate();
isSpawned = true;
}
}
}```
im gonna do so much stuff in coroutines now
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
i dont get an error also, cause when i press play it doesnt follow the player? love if someone helps me (need i to change something in this script? using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
using Unity.Cinemachine; // Vergeet niet de Cinemachine namespace toe te voegen
public class PlayerManager : MonoBehaviour
{
public static bool isGameOver;
public GameObject gameOverScreen;
public static PlayerManager instance; // Singleton instance
public static int numberofCoins;
public TextMeshProUGUI CoinsText;
// Gebruik CinemachineVirtualCamera
public CinemachineCamera VCam; // Cinemachine Virtual Camera referentie
public GameObject[] playerPrefabs;
int characterindex;
private void Awake()
{
characterindex = PlayerPrefs.GetInt("SelectedCharacter", 0);
GameObject Player = Instantiate(playerPrefabs[characterindex]);
// Wijzig de Follow property van Cinemachine Virtual Camera naar de speler
VCam.Follow = Player.transform; // Dit is nu correct voor Cinemachine Virtual Camera
numberofCoins = PlayerPrefs.GetInt("NumberOfCoins");
isGameOver = false;
// Zorg ervoor dat er slechts één instance van PlayerManager is
if (instance == null)
{
instance = this;
}
}
void Update()
{
CoinsText.text = numberofCoins.ToString();
if (isGameOver && gameOverScreen != null)
{
gameOverScreen.SetActive(true);
}
}
public void GameOver()
{
isGameOver = true;
gameOverScreen.SetActive(true);
}
public void ReplayLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
Hi! If you want to share code, make a paste bin link. Makes it easier to read :)
!pastebin
alrightt
the command is !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.
and you can see all of them in #854851968446365696
https://paste.mod.gg/zjbplrdjtkue/0 @sterile reef
A tool for sharing your source code with the world!
it doesnt move the camera 😦 so i want to remove the camera to get the full level at one screen
If you're trying to pan on introduction to a new level, you could setup multiple VCams and have a script that when the scene starts it activates the dolly camera and once that's done it shifts to the player cam
If you're trying to have it follow multiple players on the other hand you should create a players game object and put all players within that, and have the camera look at and follow that combined object
No, the meaning of the thing was to let it follows the player but now it doesnt anymore it did at first but now not anymore so i want to delete that camera to get the full level in my screen, and no i have 1 standard character
Oh so you can just leave the same camera with a single "static" VCam if you'd like. Don't have it follow anything just keep it still
I don't know what the follow does in a virtual camera, but can't you move the camera's transform?
You can just delete all Cinemachine references in your script, you don't need to control anything for that, just setup the cinemachine cam correctly in the editor
ooh alright i will try
That's where you're wrong buddy 🤣
thanks mate @crisp minnow it works 😉
I work backend, my knowledge of visuals is next to zero 👌 Well, I'm glad we got lucky this time 😉
tbf you were completely correct since the answer to "how to make cinemachine not follow an object" is to not tell it to follow that object
I'm confused now though 😆
A new question i have a sign in my game but if i get onto that sign their is nothing happening (the meaning is once get at the sign that there mus loading a new scene thats the scene and this the script: https://paste.mod.gg/bmehtekwypfo/1
A tool for sharing your source code with the world!
Is there an oposite to [RequireComponent]?
Like a [PreventComponent]
to add on top of a monobehaviour script
What you mean? Can u give an example
using UnityEngine;
using UnityEngine.SceneManagement; these 2 things isare standing
https://paste.mod.gg/wbhkxpsgoszv/0 this the script
A tool for sharing your source code with the world!
what's the issue?
like if I have ScriptA attached to a gameobject, I want ScriptB to throw an error when being added
the 2 components should never exist together on a gameobject
this feels kinda like the "unique" thing that renderers have but i can't find it, one sec...
the issue is i want to get an sign this one to load a new one a new scene*
issue is that they don't have a shared base class
I just want one script to hate another script and refuse to be on the same gameobject together
if adding script B removes script A, that's also fine
but I'd rather have an error instead
I mean you could work with onvalidate and check for other components
I guess I could achieve it through executealways awake... but that feels icky
well i found where all the attributes are, and what i was thinking of is DisallowMultipleComponent
onvalidate runs SO often though
but yeah no "disallow other component"
why can't they though? do they already inherit something other than MonoBehaviour?
i dont get it
then that will be your friend
Only runs once when you add or manually press reset on a component
i'm not replying to you there. i still don't know what the issue is
what you described is what you want, not an issue
does it not happen?
do you get any errors or logs?
you've given very little info to work with
Wait lemme explain better
So the meaning of the sign, is if player comes on to that then it have to load "Level 2" (a brand new scene) but now it doesnt do anything, the script is on it, the box collider is on it but still nothin
are you getting any of the logs in the script you showed?
public class Example : MonoBehaviour
{
void Reset()
{
#if UNITY_EDITOR
if (gameObject.GetComponent<OTHER_COMPONENT>() == null) return;
EditorUtility.DisplayDialog("Component incomatible", "This component is incompatible with OTHER_COMPONENT", "OK");
Destroy(this);
#endif
}
}
hello my people
currently I have this for the hitbox, which is working nicely
however I realized, it only detects one collision when I activate it 😦
see here, I'm hitting both, but only one is detected
so it touches multiple objects and only triggers once?
any errors in the console?
rather than activating/deactivating a trigger collider you should use a physics query like an overlapbox instead
yeah... oof
holy hell, chat gpt actually gave decent advice for once?
XDDDDDDDDDDDDDDDDDDDDDD
imo its 50:50, the hard part is filtering what is in which half 😄
it helped me fix build errors that i couldnt find at all online more than once, on other topics it fails horribly
dont rely on it too much
welp, if that's what needed
i dont get any logs or errors
never
Why my raycast depends more on world position and less on mouse? From certain spots i can rotate it on 360 degrees while on others to only like 80-90 degrees. I've tried to log mouse position and it looks correct
Here i didnt move my mouse and only moved character but ray still moved
private void Update()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); // Vector2 variable
//if (InputUtilities.PressRBM())
if (InputUtilities.HeldButton("UseAlt")) // holding rbm
{
Debug.DrawRay(transform.position, mousePos, Color.red);
Debug.Log($"Mouse position: {mousePos}");
RaycastHit2D hit = Physics2D.Raycast(transform.position, mousePos, interactRange, layerMask);
if (hit.collider != null)
{
IInteractable interactable = hit.collider.GetComponent<IInteractable>();
interactable.Interact();
}
}
}
Your DrawRay and Raycast calls are incorrect
Debug.DrawRay(transform.position, mousePos, Color.red);```
DrawRay expects one position and one direction
you are giving it two positions
Same with your Raycast
if you want to use two positions, instead of DrawRay and Raycast, you should be using DrawLine and Linecast
Oh, i thought it would use mouse position as a direction, thank u
Hey, does somebody know a way to change shadow color? I want completly yellow shadow, but I didn't find anything about it
text or background?
you need to show relevant code too.. You're in a code channel
Background, when object casts shadow
i did posted it already
A tool for sharing your source code with the world!
oh didnt see it in the second msg
yea thats my bad
this log is not printing it seems
Debug.Log("Object dat de trigger raakt: " + other.name);
do you have at least 1 rigidbody on the player?
nope it does nothing at all the whole code not even errors or sum, so yea think just gonna do it with buttons and yep i do
if you dont see errors is because there isnt anything to error on, but if no logs print at all then you have no trigger happening for some reason
Oh I see why..
You're in a 2D game
using OnTriggerEnter
Unity has 2 physics systems, one for 2D and one for 3D
OnTriggerEnter is for 3D, use this version instead
yes but the 2D version
🥳
that was the thing i was looking for 🙂 i appreciate it
Is it safe to moving a part of code from Update() to a method and then call this method in Update()? It became pretty big at this point and i afraid it may break something if i break it to multiple methods outside of it in the first place
ofc. not only is it safe but preferable usually
you're calling the same code, no reason it wouldn't be safe
This is how it should be done . . .
Yeah, i know it worth to split big code fragments to simple parts but i was afraid it may lose some data bc of update behavior (i mean constant updating a much of data)
Thank u
unless you are spawning thousands of coroutines or gameobjects in update per frame its a non-issue usually, computers are really fast
Data cannot be lost unless you remove it. Everything is stillcalled every frame because the methods are placed in Update . . .
Got it, thank u
hey does anyone know how to fix "failed clustering job" when baking lights in unity? im using HDRP
Hey, does anyone know a way to change shadow color which gameobject casts? I want completly yellow shadow, but I didn't find anything about it. I am using URP
so i've got a boot scene (additive scene stack) but its annoying having to switch scenes or go through the whole initialization process to test various parts of a single scene because i dont have my singletons in those scenes. is there a natively supported way to sort of have all of my singleton entities carry over scenes in the editor (not runtime) or do i gotta do some hackery?
can you create a single prefab out of them all?
and just drop them all in every scene and have duplicates purge themself?
check out RuntimeInitializeOnLoadMethod
you can use that to execute code when you enter play mode (or when the game starts, in a build)
I use this to instantiate my singleton prefabs
not sure what you mean about dups- dont put it in there if you have one, but otherwise, yes. @dense pasture
(which I load from a Resources folder)
i mean, if i put the singletons in every scene (from a prefab), it will run the individual scene the same as if i had done it from the boot scene, and then that way when i do run it from the boot scene the extra copies in the subscenes will not instantiate at awake because theres already an instance
this looks interesting too. so i put that on the awake for my singletons and they'll pop on no matter what scene i boot from?
No. You use that to make Unity call a static method.
if thats how you have your singleton code.. they remove themselves if an instance is already in place- yeah that sounds good!
yea im looking over it, haven't finished reading
so based on the examples, it looks like i can just have it forcibly add them to the scene if they aren't there?
You'd instantiate the singleton prefabs as the game starts
(and stick them in DontDestroyOnLoad)
right
aite that sounds about right
so prefab something like this (the "Core" parent) with a dont destroyonload in it's monobehaviour, and then instantiate that from the RuntimeInitializeOnLoadMethod call
^ I like that
rawk
the Game Controller is pulled out of Resources, and then it instantiates other prefabs
i think to avoid the scenedirector from trying to load the scene stack at runtime, check if it's on the boot scene or not
I have editor-only code that checks if we're in a non-menu scene
normally, it's guaranteed to be loaded while in the splash-screen scene
(not the unity splash screen, but another one i made, haha)
lol, btw do you do anything like split your lists of scriptable objects up into separate children on something like a GameData object? for the sake of keeping clutter down? is that worth it? i'm looking at what i have now but its a very small collection, i can imagine when each table has like 200 entries it will be a nightmare
I do have several "catalogue" objects
for example, I have a singleton SO that holds every settings category

in turns, those holds settings (and other settings categories)
i'm thinking of splitting these all up into child objects
but the parent would roll them up at runtime
Is the order of those objects important?
if you use resources/addressables you can load many similar objects in bulk
or do you just need access to them?
theres an enum that references them by index
ah, okay, so order matters
sort of
I was going to suggest an editor script that just finds them all and assigns them for you
i wrote a tool that generates the enum class files automatically and reorders them
long as no one changes the SO names it wont cause any headacheds
and even then is just a find/replace
i could also make the SOs accept a string that determines their name in the enum list
so even if the SO name changes it keeps the ref, but that could look confusing from a readability standpoint. either way its mostly idiot proof
(and i'm the idiot)
its also only really for the sake of accessing these from code. most of the things they're being used in only need to be in this table if i need a code reference
eh id have the enum in the object and at runtime build say a dictionary for safer quick indexing.
i'm doing that for most of it
well yea that part is easy, its having them in the correct order that i dont like
even if the order changes, the code doesn't need to, the enum will rearrange itself automatically
and you're serializing enum names, not the values, correct?
yup
then why
wait what
no no im not serializing anything. for the identity SOs its just a straight int enum starting from 0 correlating to the index in the game data list
and you don't serialize the enums anywhere?
Yea id just have the Enum serialized in each object and not care about their index
they're strictly used in code?
the enum values will change as the enum is reordered (if you don't assign explicit values to each name)
this is all it does
if i change the order in the game data and regenerate it'll just move them around
any use in the code wont change
the int value will thats all
there might be something i'm overlooking that'l bite me down the road but i'll refactor if i see it coming sooner than later
this IS the refactor of realizing using string names for things in my frameworks wont scale well so i switched to using SOs as ID markers
this was originally using string literals to reach out to things. now it's just the same SOs being used in that collection on game data, but with ways to pull them in code
most of these tools will just be using the SOs but i have support for custom c# script to direct cinematics too so sometimes i need to access them from code easily
yeah, that's an issue i've run into as well
sometimes it's inconvenient to reference an asset
I also don't like using strings as an index, but damn does it make debugging easier.
its easy until you change the name of "Player" to "Character" and now have to go hunt down all the cases of using that string in 500 cinematic scriptable objects
constants can get you around that problem in code, but for editor tools... yeuch
you have your "core" marked static?
is there anyway to delete player default data using UGS CLI?
I can list players and delete their accounts but it does nothing with the cloud save default data
iirc you need iterate through their keys and delete each data at that key...
ah wait you said CLI not API . oops. yeah I havent touched the cli since it came out.
What is the difference between Transform.TransformDirection() and Transform.TransformVector()?
This operation is not affected by position of the transform, but it is affected by scale. The returned vector may have a different length than vector.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.TransformVector.html
This operation is not affected by scale or position of the transform. The returned vector has the same length as direction.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.TransformDirection.html
gotta love the manual eh?
just a curiosity is this button in your inspector custom or?
yea
how did you do it?
right now im using a script i got from github to make buttons in the inspector
yea similar to mine, thanks man
Okay so Transform.TransformVector() is just affected by scale and Transform.TransformDirection() is not. So I'm assuming if the scale is already uniform then they act the same?
idk about uniform but more of them being anything above the normal 1,1,1 gets scaled by anything above it or under
since anything * 1 stays the same, if you got anything above or lowerr then yes ur vector now gets affected by that scale
Yeah, the scale is already at (1,1,1), so my issue might be coming from something else.
note that "uniform" does not mean [1, 1, 1]
it just means all three axes are equal
but yes, at a scale of [1,1,1], it's the same outcome
Yeah I realize that now, but I meant 1,1,1
similarly, if you're at the origin, TransformPoint will behave just like TransformVector
and if you also have no rotation, then...well, nothing happens
you are now the identity matrix
So, have this code which draws the direction of the velocity vector, and it works and appears smooth when I run.
I have a "simple" replay system that I wrote which records data at 10 fps, then on playback it interpolates the data between recorded frames. This appears to be working. The objects position and rotation are just as smooth on playback as when it was recorded.
I'm not recording the velocity vector data, just recalculating it the same way on playback based on the objects position. But the velocity vectors are choppy in playback.
private void Update()
{
if (_targetTransform != null)
{
Vector3 velocityVec = (_targetTransform.position - _lastPosition) / Time.deltaTime;
velocityVec.Normalize();
_lineHandle.SetValues(_targetTransform.position, _targetTransform.position + velocityVec * _length);
_lastPosition = _targetTransform.position;
}
}
void IHandleReplayStartAfterFirstFrame.HandleReplayStartAfterFirstFrame()
{
_lastPosition = _targetTransform.position;
}
Replay code:
A tool for sharing your source code with the world!
Okay so I was incorrectly calculating recording frame delta time like an idiot, but the problem is still persisting.
Changed this:
_frameDeltaTime = _recordingFps / 60f;
To this:
_frameDeltaTime = 1f / _recordingFps;
Soooo the choppiness of the lines have a direct correlation to the recording fps. If I increase the recording fps, the lines are less choppy.
I'm really unsure why that is happening, because the lines script knows nothing about the replay system. It is just looking at the transform which is being interpolated.
If I draw _targetTransform.up vector from the target transform's position it is not choppy, even at a 5 fps recording. It has something to do with the velocity calculation, which again I don't understand since it is calculating it with the interpolated position on the transform.
Are you sure your velocity calculation happens reliably after the transform is updated? Maybe call it manually explicitly after the transform update?
I'm pretty sure, the default execution order of the replay manager is set to
[DefaultExecutionOrder(-1_000_000)]
I'll triple check though
Relying on custom execution order is not ideal. Should structure your code such that you don't need to rely on it.
But anyways, the execution order is not the cause probably.
Thinking about, it does make sense that velocity changes would be discreet
What do you mean?
!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.
Is that for me, my code is already posted
Well, think of the position points that you have(the interpolated one). Try to visualize them on paper. Draw a line between them. You'll see that the longer the line is, the more visible difference is between the lines(velocities)
was lazy to find the correct channel
I may be misunderstanding, but the positions should be spaced out relatively the same between update loop frames no matter what the recording fps was set to because they are interpolated between recorded frames.
otherwise the replay would look choppy too
It doesn't matter how they are spaced. What matters is how long the velocity vector is. Draw it on paper and you'll see what I mean
I'm just normalizing it anyways though to just get the direction
It is not because the difference between the positions is small enough for the brain to not perceive that it's discreet. But the velocity vector the longer it is, the more distance there is between the tips of the vector when you turn. This difference makes it easy for the brain to perceive the discreet change.
Well, 1 unit is already big enough. In fact, I think it would look like that in any situation. Even if you just draw the velocity of the original(not replay) object.
Watch the video, it is smooth normally (not playback)
I'm not drawing the magnitude of the velocity vector, I'm always drawing it with a fixed length with the direction of the velocity
It's not ideally smooth. It looks a bit better probably because the differences are more precise.
It doesn't matter. As you go through position -> velocity -> acceleration, the difference between the vectors would get bigger and easier to percieve it's discreet nature. Especially if you're calculating it from limited data.
That is what I am not understanding though. How is the differences vastly different in playback? The difference between update frame 1 interpolated and update frame 2 interpolated between recorded frames should be similar to when it happened in realtime
Why does drawing the forward vector or up vector appear smooth though even in playback?
Because interpolation might not reflect the actual positions during the recording. Imagine that in original you have positions in an arc. Then you take the points at the edges of the arc and interpolate between them. All the points in between would be on a straight line instead of an arc. And then when you combine 2 segments like that you have sharp turns in between.
Because it doesn't rely on the points difference.
That makes more sense
I'll record the velocity into the replay as well then
You could record just the velocity and recalculate the positions at replay time.
Or even acceleration
But ultimately, you're gonna lose data/precision if you skip frames
Okay thanks!
Yeah, actually, with velocity or acceleration, the replay is likely gonna go out of sync(unless you record them every frame)
Yeah that makes sense
Yeah so recording the velocity and using that in playback makes it smooth, so I guess the lesson today is don't do calculations on recorded interpolated data lol.
Thanks again @cosmic rain
hi, I'm asking for help since this problem has been plaguing me for a day
im having an issue with navmesh agents where their walkpoint is inaccessible, the agent won't move, yet isPathStale, CalculatePath and pathStatus all return that the path is valid
when the agent is selected, the gizmos showing the destination and path flicker
not much we can do.
well how are you setting the destination and all that
by any chance are you recalculating every frame
also you always get best results when you use SamplePositon
currently im picking a point, offsetting it by a random amount, and making sure there is ground beneath it with a raycast
sometimes it does pick a wall which is fine, but even with a partial or seemingly complete path the agent won't move sometimes
I shouldn't be? once a destination is chosen it should stop the loop from searching a new one
if you call set destination every frame that can be issue, I think they changed something that now makes agent stop when it recalculates every frame
ahhh
let me see
it seems much better now! no flickering, and the agent always moves until the walkpoint becomes truly unreachable
one more question I do have though
in this case, the destination is unreachable, but a partial path is formed
is there a way I can check if the agent has reached the end of the partial path?
nvm! found a way
thank you both of you, it was really helpful
nice !
just out of curiosity and seeing If what I had in mind was true, what was the way?
apparently .destination returns the closest available position, not the one you've set originally
interesting
ermm at least it's what ive seen from a couple posts online, I have some work to do to properly implement everything but I'll post here again if this doesn't turn out to be true
dont want people getting the wrong impression
you can use it to set the destination, but unlike SetDestination, you can use it as a variable
where as SetDestination is a method
they both return value, but destination returns you the position
SetDestination returns a bool
yep! seems like it
don't sleep on SamplePosition 🙂 its a good method to use to give better accuracy to calc
oh right let me look into it
for example Clalculate path wouldnt work properly for me unless the two points were run through sample position
im struggling to understand its purpose?
I wouldn't worry about it now, you might need it later for more advanced purposes.
it just returns the point onto the actual mesh from your position . You might need to make enemy go to a point on navmesh and if its not close enough to the navmesh this helps it "snap" on to the navmesh . Useful also if you don't have something solid underneath or anything to raycast on but still need a point on the navmesh
ohhh!
I'll definitely keep that in mind!
im now having success purely going based of off the closest point to my intended destination, but this is probably because i just want the enemy to walk randomly rn
im sure there's a very good use for what you're suggesting
yee i have a crab/spider type enemy that jumps from sidewalls navmesh to ceiling navmesh then to floor navmesh, sample position is a must for me 😅
neat!!
Hey guys, I got to make a game!
Hey, does anyone know a way to change shadow color which gameobject casts? I want completly yellow shadow, but I didn't find anything about it. I am using URP
That's actually a little tricky as far as I know. You either have to modify the shadow data directly if you truely want to modify the shadowing, or go about it an alternative way like post-processing, or using masks
duplicate the default lit shader and change shadow colour from there?
this shader needs to be applied to every mesh that casts and receives shadows
Hey,
Is there a way in Rider to get extra info / documentation on the popup that shows up when I hover over methods, properties, etc... that Unity made (or even my own documentation for my own methods, variables, properties) please ? Because the little popup right now is borring and doesn't give much info
Please ping me if any answer 🙂
I know that it's tricky, do you have a way to modify the shadow data, I want all shadows yellow, so I can just change all
I tried creating shader with custom color, however it either didn't work or just changef everything to yellow.
Do you maybe have some example somewhere, I wasnt able to find anything about it
Shadows are calculated in the pixel shader of a lit material. You'll need a custom lighting/shadow calculation for that.
Gizmos.color Do properties like that reset between each instance of DrawGizmos method?
I think not. But you can test it real quick.
whats the best json package for unity?
trying to serialize lists with jsonUtility but its a shit fest
if jsonutility isn't cutting it for you, then use json.net. however jsonutility shouldn't have any issues with serializing a list provided the list isn't the root object, it must be part of another object
yea my list is the root object
i'd have to create a wrapper around it
but its quite the shit fest to read no?
then just do that, it takes 2 seconds 🤷♂️
you could even give the wrapper object an indexer so you can directly treat it like a list, or implicit (or even explicit) conversion operators to make getting to/from a root list object even easier
Hi! I'm facing an issue with my attack speed in my game. Basically, I want to have different weapons, with different movement speeds, however, although my code is correct (I have confirmed this several time by checking values, as well as the actually rigid body value) it does not translate to increased movement speed in game. I'm not sure what's causing this as all the values are correctly set. Here is the code for my character controller, and my attack Script where I'm setting these values. https://paste.ofcode.org/smdr44nEFRFmNFfiQeSiXz. Thanks in advance!
P.s. I use a rigid body to move my character, with rigidbody.velocity
Pps. Please ping me if you have a slotuion otherwise I wont see it XD
Does anybody else use the Kinematic Character Controller?
I'm still having trouble with Swimming...
That is so weird. I have a script that is in a folder named Editor, but it gets included in a build
why could this be? Is it the fault that It's a separate assembly?
building right now results in a compilation error, but wrapping the script inside the Editor folder in #if unity_editor solves the issue
I'm just confused why the Editor folder is included in a build
Unity 6000.0.37
so newest one
What is the script doing? is it really an editor script?
it's an editor script yes
and wrapping the whole file in #if unity_editor makes it compile
And it derives from : Editor?
😄
but close enough
why?
the script works, it's not the issue
and removing it from compilation via #if unity_editor works
but why does the presence in a folder named Editor doesn't exclude it automatically
you dont have to repeat that all the time 😄
I am wondering, if your editor folder is somehow misspelled or something
Can you show your script, your propertydrawer?
is it in an asmdef?
yes
you'll need an asmdef for the editor folder too then
🙃 I suppose so
you're telling unity explicity which assembly to put it in, and unity is doing what it's told 😛
yea that's fair
yea an Editor folder inside an asmdef doesn't do this magic anymore
Yeah I was very confused by this when I first started using asmdefs too. You need to create a separate editor assembly and on that editor asmdef untick all the platforms except editor
And, you can name the folder whatever you want at that point.
hello, i modified a scriptableobject script, and it doesnt think its a list of a new item, but the old item.
What do you mean by "new item" and "old item"?
You probably have a compile error. Check your unity console.
ScriptableObject in inspector still uses List<Item>, which is just a guid and itemdetails scriptableobject
Got any console errors? (show us a screenshot)
i know how to debug, just forgot to check console, and forgot to use refractoring when changing the scriptableobject.
totally my fault
Oh, I didn't see Prae had already said to check the console
Ok so i dont know if this is possible but i'll try to explain what i wanna do.
i think it's a bit time wasting for me to always create a script just to move a single float on a single object. there be various reasons to do it, but i never could specifically use the same script on all the different scenarios.
So i was wondering, is it possible to create a script that lets you plug any float to the variable to be modified without having to create a specific one?
i mean like, within the inspector, take the x on a transform and drag it onto the designated property elsewhere on the inspector and just let that new property handle the value of the float?
like, the idea was to be non-specific on the float but being able to drag the float to it will just make it manipulate it
Well if you wanted some flexible system you could say use reflection and provide field/property names to dynamically read values but it would be prone to breaking.
Other way is if you have custom components that can provide this data you can use an interface or some common way to share the data do set it up in inspector only.
this is all a bit vague. "move a float" is wishy washy
You could make a function that takes an Action<float>
and modifies it in some way
you could use DOTween
there are many options, but currently the question is a bit too vague to be answered concretely
im finding it difficult to explain. but, you know how you can create a property field that can drag a component or game object or transform into the field in the inspector? well i was hoping to be able to do the same with a float or vector 2/3
the problem is that floats and vectors are structs
they are value types
But what you can do is use interfaces and delegates
well regardless you need a way to serialize the property or field name
e.g. name. But no idea if you could even make this doable via drag/drop without some custom popup to let you pick a field/property
"floats are structs" feels.. wrong, is that really the case?
they are a value type
ugh, i hate it
managed code moment
im not too familiar with the term delegate or interface (im a bit illeterate on the terminology of c#), but the main idea i had was probably to get the component in question and find a way to list all of the public variables using the the type of value, like vector 3 or floats.
then i can just pick the one i want to modify from the array
The animator does something similar to this yes but they use reflection
i thought it was like, value type = { primitive type, struct }
it's not generally a good practice
turns out all primitive types are structs
so value type == struct
i hate it so much
reference type == everything else
looks like all "primitives" are actually structs.
We have strayed too far from C
Another option is to use sort of a referencable wrapper object instead of a regular variable
then you reference that thing
that's the idea behind the Atoms architecture
i mean c structs are just a list of other types so.. i guess primitives would be 1-member structs but i don't like the thought of that LMAO
float a = new float() is valid too 😆
that's pretty interesting. i'll see if i can find anything on it being used. dunno if i wanna put this in blind lol
Example of usage: https://unity-atoms.github.io/unity-atoms/tutorials/variables#creating-a-simple-health-bar
Variables, Constants, and References
noooooo 🤢
Can that allocate the float on the heap?
no
structs have constructors too
Then it's cursed
it just creates a float with the value of 0
yeah this is pretty much what i was looking to do. reference a variable like that, and be able to let my script just handle the rest. so i dont have to create too many specific scripts for scenarios
new Object() { float x; };
🙃
(does that work in c#)
probably if you take that last semicolon
also @leaden ice i don't mean to ping you but i just realized that you have been like the main person answering my questions over the past few years. so here's my heartfelt thanks ❤️
you should be aware, if you use the SO architecture (atoms) for runtime mutable values, you can very easily murder your project and make it unmanageable (the paradigm is very powerful), but if you just wrap your primitives into SOs to enable your drag/drop in the editor for runtime-immutable values, you've essentially created a form of type-object with added configuration and that is a very powerful and generally required architecture (if you want to stay productive).
yeah, this is why i was hesitant on this particular thing. i simply wanted to drag an drop any float or vector into the field the same way i would do a component and just let the rest of the script do what it would do to the value afterwards.
im reading up on serializable objects and serializable reference as we speak. it feels like it's sorta where i was looking
well, if you change public values on SOs, best of luck to your mental health
lol that's already in question with a lot of things i've been attempting
SerializeReference is also one of those things that explodes like a hand grenade in your pocket if you aren't careful. If you try to be clever, unity has many hidden traps waiting for you. Its great fun finding them all.
yes, recursive references, much fun
there is a reason why traditionally you give everything in a game an ID and communicate between objects only through a mediator via that ID, not via direct object reference.
unity does that internally, but in c# land we're happy to make direct references, until it comes time to save & restore game state, add multiplayer or migrate between versions of that game state.
ah... well i'm probably going to back off from this one, but i do want to read up on this a bit more
Anyone here have a paid subscription to an AI model for game dev? If so, which have you chosen and why? I'm trying to pick the "best" one to spend my money on and am having a hard time deciding
(assuming you're asking about generative ai for code) i would recommend saving your money and just learning yourself, genai isn't as useful as it's marketed.
you need experience to filter the results anyways, so if you don't have the necessary experience, it'll end up being a detriment.
I have experience, I appreciate your advice but you're making some assumptions about my background there
i am, because most people asking stuff like that have that (lack of) background
people arent gonna list out every possible case. if you dont want people to assume, then state relevant info beforehand.
I dont think this question is really suited for this channel. though from what ive seen, most people will use Chatgpt or copilot. Ultimately its up to you to
. Regardless of which you go for, they're all gonna spit out garbage
ChatGPT is probably the best one, though when it comes to any LLM, its less about how good they are, and more down to knowing how to use it to get the most out of it. I dont think any of them are better at game-dev than another, just some are better at generating code than others
not really sure what your reaction is for on my previous message. 🤷♂️ this kind of question just isnt what the channel is for in the first place.
if you dont think AI spits out garbage, i have doubts of your experience
i would rather not hook up the infinite spam generator to anything on my computer
It was for the passive aggressive tone
but anyway thanks folks
Im off of here
mmm im not seeing any aggression there, they just stated a fact of asking for help
It is projection, probably.
I'll use gpt sparingly just to touch stuff up or if im too lazy to clean up a function, small tasks like that I find gives pretty reliable results
In any case, not a coding question.
i usually hear that is not good to use async in unity, but is it ok in this case:
I have a component to manage other components forming a sate machine
when a component completes a task i want to inform the manager, that manager will then check the state (involves a loop through certain components and check their state), so i thought it could be good idea to make this "message" async without await to avoid blocking the thread
note: its not implemented its just a thought yet here is pseudo code
if(something){
_ = assetManager.TaskCompleted();
// some other small tasks
}
public async Task TaskCompleted()
{
AssessState();
}
void AssessState()
{
//depending on state loop opver relevant components and if appropriate go to next state and trgger actions on next state (basically just setting flags on those components)
}
awaiting doesn't mean you block the main thread, just means the async function is gonna continue execution once the task finishes.
if you want to do something after a task completes, await it
Async is not bad in general.
But there's a huge chunk of missing information, such as what are these long running tasks?
also dont do _ = Func() you will find out the hard way why you never see exceptions in the console
I find it to be...a bit mysterious
it reminds me of how I felt about things like unity objects becoming null when i was just learning the engine
i can't tell what is and isn't allowed
Async is useful and exists because it makes writing code easier vs the alternative where you have callback hell.
yeah I don't use it much myself but many others do
I stick to coroutines which I have a better understanding of
if you understand coroutines then you can use async
Sorry, i meant i dont need to await, the async is to not block
I mean I understand async, but I don't understand the little nuances and such as well as I do for coroutines. For example the exception handling pitfalls
you can use .ContinueWith() to execute something after a task completes if you really wish
If an un awaited task throws an exception, unity isnt able to "catch" and report it for you.
If you await an async function and it throws an exception, it will be catchable at the call site still.
UniTask solves this problem with exceptions with its .Forget()
I dont think i was understood. I have this method i wanna call but i want to forget i dont care about what happens there, but regarding the exceptions maybe i should just set a flag and forget the async
I was just hoping to make the state assessment in the same frame
use UniTask for tasks instead to solve the issue
public async UniTask DoThing()
{
await UniTask.Delay(TimeSpan.FromSeconds(1000));
}
public void Start()
{
DoThing().Forget();
}
Oh its new to me, ok so i can use unitTask as regular tasks , and use this forget() will continue execution of start() regardless of the duration of the task
UniTask is a better "async task" for use with unity.
The .Forget() means exceptions will get logged for us. It doesnt affect the task runnning un awaited or not.
public async UniTask DoBadThing()
{
//This is bad and will freeze the main thread
while(true) {}
}
public void Start()
{
DoBadThing().Forget();
}
as a reminder, tasks still run on the same thread (usually) and cant just go on forever. The example above still freezes the main thread
Isnt that the same behaviour as a regular "void"? I mean i dont know when the unitask would run. I have to read the documentation on that but i cant rn, just to make it clear, i am calling DoThing() on update, its not infinite loop, lets assume its .05ms(fictional) but i dont want to hold the update method as there are many other objects with an instance of the state machine and it adds up, the result of the "assessState" will just set flags after it does its work and it will not affect anything on the same frame and the next state is not active and only thing it can happen is next state is activated on next frame
It is funny how little I do any multithreading. If I need some complex operation done quickly I'd just let the gpu handle it
coroutines let you run code over many frames cus when you yield it "pauses execution" for the function and unity comes back later to continue it.
Async can do the same when you await something such as await UniTask.Yield() to let us wait till the next frame.
The UniTask delay/yield functions use the player loop so they work basically the same as coroutine delay/waits do
I think I was having problems with web exports at one point with them, but maybe that was another issue
Hmm . I didnt understand is if its worth doing this, as i dont want to await, i mean i want it ready before next update on same object, maybe i should await it on late update or something but that only applies if its not blocking the update
you are making less sense. can you show some code to demo what you want to do??
I showed
Less sense? I said from start i dont want to await (on update) i got confused because you say unitask blocks the tread, i didnt understand if it blocks the update
you can always check conditionally then break out the execution loop if that's what you're asking
like if you wanted an infinite cycle until you decide you want to yield from it completely
okay let me give a better example
I am not asking about breaking any loop
public void Start()
{
DoThingOverManyFrames().Forget();
}
private async UniTaskVoid DoThingOverManyFrames()
{
while(this != null)
{
if(transform.position.y > 0)
{
Debug.Log("Thing!");
}
//Wait for next frame
await UniTask.Yield();
}
}
I said " send a message " that will trigger a method and that method takes some computation, not much but there are lots of objects doing this, but its a message, no await, no return, just dont want to block execution of updates
by loop I mean that it doesn't block the thread, but it'll always execute this logical sequentially every update until you decide you don't want to anymore
Lol but i need this loop every "message" its not over many frames, i never said or meant that is supposed to last many frames
The message will not be sent every update, on every object,, its conditional
you are being to vague still i dont really get what you want to do
How vague? Call a method and continue execution without waiting for it to complete or any return
I dont think this needs any context really
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Awaitable.html
Well, if you're looking for actual background threading then Unity does provide that if you don't want to use c# solutions
not sure what you're looking for otherwise but it sounds like you do want to do a lot of work as quick as possible without blocking the main thread, so that's probably it.
you can do Task.Run() to execute code on a worker thread (not main thread) but you cannot interact with most unity apis it will just throw an exception
Awaitable is unitys own Task replacement just like UniTask
I can use c# i just dont know when i shouldnt in regards to async. I read briefly some documentation but i will continue this tomorrow thanks for your help
Does anyone know of a way to get BuildPipeline.BuildAssetBundles to not create an extra empty bundle file of whatever the destination directory is? If I have three bundles and I build to a directory named win, I end up with four bundles and four manifests, one of them being an empty bundle named win. It's kind of annoying to always have to clean up afterwards.
Hello, I'm looking to use unity Custom assembly system, bc i have like 30s compile time with a simple project. The problem being, i cannot use the assemblies because the built in assemblys are not in my project, and when i add a assembly definition to my folder containing all my character stuff, it tells me that it cannot find InputActions. how do i force unity to put all their scripts into my project so i can include it in custom assemblies
does an error happen if you try to StopCoroutine("name") a coroutine that has already stopped by reaching its end?
im trying to set up a failsafe that stops it before trying to start a new one
the error you got is cus you have to add references for your new asm def to ref another asm def.
e.g. add a reference to InputSystem to be able to use input system code in your new asm def
the default Assembly-Csharp auto references all of them for you hence you not needing to do this before
Like this:
StopCoroutine("Blinker");
StartCoroutine("Blinker");
if this doesnt work id have to make a coroutine variable and check if null, i assume?
or does a finished coroutine still occupy the Coroutine variable space?
no, no error
but really don't use the string version
the string version is bad
https://i.imgur.com/rJ1lvOh.png
[Button(enabledMode: EButtonEnableMode.Editor)]
private void OnValidate()
{
foreach(Renderer render in materialRenderers)
{
render.sharedMaterial.SetVector("RelativeCoordinates", transform.position);
EditorUtility.SetDirty(render.sharedMaterial);
}
SceneView.RepaintAll();
}
Can't seem to update this material in code for some reason. Even at runtime, which could itself be another issue, I'm not seeing any changes from this material instance itself.
its _RelativeCoordinates
The Reference string is the appropraite one
which is really annoying and silly
like _MainTex
IDK why they give it two names
been a minute since I've accessed this stuff directly
https://cdn.discordapp.com/attachments/288887968960086016/1339358915954999336/Unity_742E997g2a1.mp4
Worth it tho. Physicless grass ;OO
Would be nice if shader graph had those property binders that the VFX graph has to just reference stuff directly on the editor
How do I smooth an unsteady incoming integer data stream so the output is gentler?
is this networking related?
if you have some statistical knowlegde about what clean data would look like you could use a kalman filter, interpolation, smoothed reconciliation or some simple exponential smoothing, but it depends a lot on what value ranges you are dealing with and whether the time-interval is unstable (unreliable connection) or the values themselves (noise).
I am taking a data stream from a set of pixels in a video, with data in the range of 0-255. The instability ranges by about 5.
I realize I am talking about noise
there are many denoising filters for pixel data, google will yield an abundance of results
this looks useful as a starting point: https://vciba.springeropen.com/articles/10.1186/s42492-019-0016-7
With the explosion in the number of digital images taken every day, the demand for more accurate and visually pleasing images is increasing. However, the images captured by modern cameras are inevitably degraded by noise, which leads to deteriorated visual image quality. Therefore, work is required to reduce noise without losing image features (...
Hello, i moved my scripts into 7 different domains that at most reference 2 other assemblys. However, that doesnt improve compile time, i still take 20s to compile to run, how can you improve compile time using code?
you're certain that it is the compile time that is taking that long and not the domain reload or something?
i know that my scene reload takes 2s, and this domain reload happens everytime i edit any script i have. the point of assemblys is to reduce this WILD compile time
domain reload != compiling
what can cause this massive of a domain reload besides my scripts, i have a simple scene with 5 trees, 1 100 by 100 untextured terrain, and a player character
memory leaks
that would be it, wouldnt it.
do you have a lot of static members? because that can increase the time it takes to reload the domain
if you restart the editor and its faster, you probably have a leak of some kind
you could also disable domain reload
static members of classes? no i do not have any static classes, i have 1 scritable object with 5 members but thats it, restarting editor now.
but after compilation, you still need to reload
from what you describe you should be entering playmode in < 10 seconds
Has anyone here thought about something like this before? I feel that it would be very handy to have an animation track in Timeline that can persist if the timeline is paused.
Notice how the characters still do a "wait" animation while the cutscene timeline is paused instead of just stopping their animation?
I have a bit of a plan on how to do it, but I'd like to know if someone else has thought of this before me.
Seeing this scene takes me back to the first time I played Twilight Princess, shortly after its release and on my brother's new Wii. This has been my favorite game ever since.
Please enjoy my selection of cutscenes from Twilight Princess HD. You can find the playlist here: https://www.youtube.com/playlist?list=PLluwu6OC0qmfDTQQnqmIUN_jVqNiTtN0...
that would simply be an animation state that plays a loop
Ohh i did this once! made an animation continue even when the timeline was paused
its a memory leak somewhere, after restart takes .5s to start game with domain reload ill find it
Yeah, something like that would definitely come in handy
this leak could potentially be anything or anywhere, its not necessarily in your code
Basically it would detect the current anim clip in a track and it would constantally change the start/end offset to make it still "play" the animation
it just means that unity evaluates way more items than needed/expected
yeah, good thing i learned to use assembly definitions early, but just sucks about the domain time. i wish domain reload would ONLY reload the exact script i editted and nothing else.
I feel like unity could have made this a feature where the animation could keep playing and loop even when the timeline is paused but hey ho
common leaks are from new Texture2D, new Mesh, new Material and assigning/reading .mesh and .material without destroying the instances/automatic-duplicates. Or from holding references to any of these in managed shells.
i do not have anything editting mesh, the only thing i do have is to draw the boxcollider of a plot using Vertz tools, so that may be the leak
D.raw doesn't leak unless you make it leak
you seem to be confusing domain reload with compiling. they are two separate processes. domain reload is resetting the state of the entire code environment. compiling would only be affected by the assemblies that need to be recompiled
thank you for the explanation, i just wish it wouldnt domain reload on change of a single script
this is for you then https://hotreload.net/
i really have no clue then on where the memory leak is, probably have to profile for a bit, because i myself arent doing anything that concerns meshs/materials besides assiging them to objects
oh thats super super helpful
its a very common problem experienced by almost everyone. personally i aim to avoid leaks and silly memory mistakes, but still it helps to restart unity twice a day.
this wouldn't prevent a domain reload on a normal recompile though 🤔
I restart unity maybe 5-30 times in a day due to my lovelly infinite reloading domain bug 😦
and by restart i mean kill process and re open
no, but it avoids many recompiles when just tweaking stuff inside methods
infinitely reloading domain seems like a infinloop problem no?
its also incompatible with debugger use... but at least it makes adding a debug.log very quick
yeah, i can deal with the 1s to recompile/domain reload after restarting my editor, but i will keep it on hotbar if i ever need it
since theres drawbacks to hotreload
building your game so it supports disabled domain reload is helpful
but you gotta learn to live with 10-30 sec for enter play mode after re-compile on projects of a decent size
yeah, my game problably doesnt even need domain reload rn. i disabled it on play mode enter. the problem was domain reload on script compliation
just be glad its not a C++ game
then you'd be waiting 20 minutes
i read somewhere that they made the killzone games without any kind of real level editor and iterations (change of value to ingame test) of 2+ hours
that just sounds like true pain. and btw yeah i checked and my game is all set to not need domain reload rn. i always found static variables not very useful with how mono scripts have to handle finding other mono scripts
sbox's hot reload is amazing so hopefully we can get something this good when unity ditches mono
Does anyone know why when the player.transform is moved to a position after touching the spikes the linecast suddenly doesn't detect anything with the Player tag anymore (even if I make a new game object and assign the player tag to that and set it to what the linecast is targeting)
What happens when the player hits the spikes?
Player's transform is set to the latest respawn point they touched
I bet the player turns into Player (Clone)
ok i was probably wrong
anyway time to start using Debug.Log
Hm... not being re-instantiated. The log seems to show the line is hitting something named NoEnemyPass? Or is that a different enemy line?
That's a collider where the player can pass through but enemies can't, it's placed here in the scene, the enemy pathfinds around it normally
Unsure if the log is just not updating, or if it's printing every frame, but the last thing the raycast hits was that object
Check with the console open and see if it's detecting that object, or if it stops detecting anything alltogether
Could also be that _respawnPointAfterSpikes is at a weird Z position that the player then gets teleported to
Check to make sure your respawn point is at the same Z position as the player and enemy
Yup that was it thank you!
does anyone know how to make variables in class reference a outside datasource? Like the bindings for ui. I pass a ref to a data object, set variables equal to the data object, but they dont ref the source, even a Quaternion and transform. i can pass by ref keyword but i was told its unessisary because objects are already pass by ref.
The simple answer is: you can't in C#
You could use a property that access the target field/property in real time though
why cant you make 2 references reference the same place in memory?
Transform is a reference type, so you can pass around references to Transforms.
Quaternion is a value type. No references for value types.
why not?
can you write your home address down on two pieces of paper?
You can if they're reference types
But not value types
int is not a reference.
Transform is.
If you actually have references you can.
instead of duplicating all this data just keep a reference to the PlayerData object.
ah ok, so i need to have an object wrapper.
this whole Bind method should just be:
myPlayerDataRef = data;```
assuming PlayerData is a class
will do.
You really don't want that in a language that promotes memory safety. It's very easy to get sigbuses like that.
this isnt rust
Left to our own devices, mankind will re-invent the pointer hell they have only just escaped from
I love rust and the borrow checker and i like Cpp too
i love java for its ability to have 2 objects reference the same data, and that allows the data to only have 1 place, but 2 different objects can still interact with it.
c# has this too what are you smoking
i cant do the thing with references im able to do in java
I'm unsure what you're referring to but if you change the target reference for either language, it'll no longer be referencing the same target.
yes, im saying in java i can just choose for a float to be pass by ref if i want it
In java everything is a reference type. This is also one reason it loses in performance to C#.
void MyFunc(ref float f)
b.value = 3;
var a = b;
a.value = 5
Debug.Log(b.value);//5```
ah, ok, then i am mistaken.
Just booted up a new project, got hit with this without doing anything
either update all your packages or delete the version control package if you're not using it
How do i delete it?
From the package manager
1: windowskey + shift + s = drag a box to copy an image from your screen
2: ctrl+v directly into discord
Removed it, error stayed
I don’t have discord on my pc
... i can see the icon for it right on your pc :p
also can be used on the web
Okay, I have discord but I am logged into an old acc without this server which I don’t remember the password off and if I need to join this server I have to write my password which I don’t remember
But that acc is also is the owner of my server so I can’t just log out and lose it
close unity project, delete Library/PackageCache folder, re open project, ???, profit
is unity 6 worth upgrading to? I know that unity tends to change API and i'm trying to make that decision since i'm reading its more stable.
I wanted to start looking into DOTS since some of my projects involve mass unit spawning, and trying to make a gameobject with a tiny class still lags when it hits like 50-100k units, even with the most rudimentary logic.
There's also the issue of having to debug any plugins or api additions/removals which could be large swaths of code or very little. I'm mainly interested in better performance and more fleshed out systems like DOTS/ECS if that works (last i read animator is still not supported by DOTS and it requires a custom class?) and the whole issue of dots and gameobject interactions.
Getting alot of mixed information online. Anyone that has a large project and has upgraded, any major issues or notable bugs compared to 2022.3 (unity 5)? Also curious if the debugging is any different or more accurate, since that's generally a tricky thing to track down sometimes even with stack tracing. The plan would be to clone my current project then import/fix any issues.
one thing to note is that unity 2022.3 is not unity 5, unity 5 is a version that came out a decade ago.
but if you are in the middle of a project it is usually not advised to upgrade to a new major version unless there is some specific feature you need so that you don't have to go through all the trouble of ensuring all of the assets you use are compatible or updated for the new version.
as for your DOTS related questions: #1062393052863414313
ah... I forgot to clarify that the data stream is not the video itself, but rather a 512 long array of raw DMX values decoded from the video every frame. The array is the thing im trying to denoise
primitives are not references in java
most languages have this, just as a fundamental part of how memory works; pointers in c/c++, abstracted up to references in c# or java and then just integrated as objects in js
Ah, I see. So there are "value types" in java as well. So they were probably using a wrapper object.
value types don't have it, ie fundamentals in c/c++ or structs in c# or primitives in java/js, but there are ways to get a pointer/reference/object for each of these cases
yeah, java has wrapper classes for each of the 8 primitives; beyond being references, they're necessary for generics in java
does sprite atlas batch sprite animation?
If you add all the sprites of the animation to the atlas, sure.
Hi guys, I'm having a translation problem with Asian languages (Korean, Japanese, and Chinese – both TW and CN). Russian and Latin are working fine, but I'm facing issues with these. Does anyone know anything about this?
I also tested other fonts, like NotoSans Korean.
same issue
never mind, it has altas res, I forgot to test it.
Next time go to #📲┃ui-ux
if you make a copy and have good internet or time to spare i suggest you try. 100k objects is exactly the strong suit of DOTs, you will have to learn ECS and probably change your way of programming, but i dont know the actual state of DOTs for your purpose (animation) at the moment as i only used it in preview and not with animations but it was awesomely powerful for huge amounts of "entities", i believe its only better since it has been released..
Note: I dont know if you watched this, but seems that animation its possible in DOTs didnt bcs i am not using it but i follow him so i knew this was out there ||https://www.youtube.com/watch?v=KvabbZKrUHk || and this is just a plug to a course on the same topic ||https://www.youtube.com/watch?v=P01egjRl2cs ||
Hey, does anyone know a way to change shadow color which gameobject casts? I want completly yellow shadow, but I didn't find anything about it. I am using URP
Not possible. It also doesn’t make sense conceptually.
I want all objects casting shadows to be yellow
Not only some
I have a rotated rect (it's technically a camera view). And I need to project positions outside of it on it's edges.
Rotated rect is represented by 4 Vector2 (each vertex of rect).
Any idea how can I do that?
How do I prevent Unity from using 100% of my CPU when building shaders(Windows, Unity 6)? nothing seems to work.
convert world pos to local pos (for this rect), then its easy to clamp the positions within the min/max
hm, how would I convert world position then?
oh, I think I know
If you have a Transform you can use that, else a matrix is easiest if you are comfortable with them
well, what I had in mind is different: I know that each point is associated with 0.1f or 0.9f of viewports
so I thought I could just convert using those maybe
I do wonder if there's some value to that. It keeps you from just changing random shit until the game appears to start working.
This may be an "uphill both ways in the snow" take
there's a "realtime shadow color" option in the lighting settings, that would be the easiest way i guess. unless you have baked lights too, in which case its a bit more complicated i think
has anyone had issues reading pen tablet delta values with the new inputsystem? finding it spikes from regular values like 1-5 to 80 or 100 for very minor movements(that should be 1-5), doing similar mouse movements doesnt have the same issue
are you getting inconsistent results, or are they just very large?
inconsistent results
are you happening to use update to update values without time.deltatime? specifically for the pen movement
A delta value should not be multiplied by the frametime
since it's already an absolute amount of change, rather than a rate of change
It forces you to plan and think. The downside is that trial & error (iteration) and learning is impaired. Might also be why such productions rely so heavily on writing and on-paper design.
How do I optimally add Unity Events to a prefab (specifically one that I place via the editor instead of spawning it via a non-prefab spawner)?
private void Start()
{
collected.AddListener(ScoreScript.Score);
}
public void OnTriggerEnter2D(Collider2D collision)
{
ScoreScript.Score();
Destroy(this.gameObject);
}```
ScoreScript is a singleton class and Score so far does nothing but increment an int score and print a debug message. Adding the event didn't seem to work, but directly invoking the static message does.
optimal for what? are you asking for a better solution here or is yours not working at all?
your code there doesn't show where the event is invoked at all, so it's hard to see the whole picture
...nvm, I'm dumb. That would be the issue. The event should be invoked in OnTriggerEnter.
ah 😄
whats the purpose here anyway ? is this just to broadcast the score ?
wouldn't ScoreScript be the one with events?
How so? The cup is the item that gets collected.
scorescrpt is the one tracking the score no?
public void OnTriggerEnter2D(Collider2D collision)
{
ScoreScript.Instance.Score();
Destroy(gameObject);
}
//score script
public UnityEvent<int> OnScored;
public void Score(){
myScore++;
Debug.Log("Scored")
OnScored.Invoke(myScore)
}```
So the prefab is only pinging the ScoreScript to make it do its thing and send out the Event?
The UnityEvent<int> means that the Event can pass on int parameter when it gets called, right?
the object to be collected just tells the manager interested in it, "I was collected" do whatever after
correct
a listener can listen even if it doesn't need the value exactly but is interested in the event, Eg a Sound player
if it has that static instance to be accessed with you can do
ScoreScript.Instance.AddListener so this event
//Another script like UI or Sound Listener
void OnEnable(){
ScoreScript.Instance.OnScored.AddListener(ScoredEvent);
}
private void ScoredEvent(int score){
Debug.Log($"scored! do something from here");
}```
or use the inspector too. you just cant make event itself static for that, use static instance of class that contains the event, w singleton pattern as shown ^
So the collectible notifies the ScoreScript by invoking its static method, then the ScoreScript broadcasts an Event, and everything else that cares aobut the Event subscribes to it with AddListener or dragging it in the editor, correct?
Sorry if it sounds like I'm just repeating you, but I learned that I need to be able to paraphrase/repeat stuff in my own words for my understanding.
Also why in OnEnable and not Start or Awake?
just habit. Normally my objects get Disabled so its good peace of mind I unbsub when they are disabled
I normally do :
OnEnable => Subcribe
OnDisable => UnSubscribe
sometimes I use Awake though . Depends on the situation but mostly using onEnable/onDisable
I generally don't use Start unless whatever I'm subscribing to needs to set itself up in Awake
event then I rather just make the ref get bootstrapped in or have the singletons have a slight sooner exec order
