#archived-code-general
1 messages · Page 432 of 1
does anyone know why
what
wut
i need help with something
chat what the sigma
You probably have lighting disabled in the scene view.
This is not code related btw. Move to #💻┃unity-talk or #archived-lighting
my bad
how do i do that btw mind if i ask
i cant find it
Is any one know what import do I need for ECS customized shader to support Dots rendering? I can not find any information on the official documentation?
Click the eye means hide it, finger means make it can not drag and select in scene view
Oh, the reason why it looks different is that Light only show up in run time
which means that it will have light effect in game mode
but when you editing it, the light is not rendering for you.
when you're using a regular Tasks, they don't know exactly whether the continuation should happen this frame, next frame or start of frame .. basically it's out of sync with the main loop
- you either want to roll your own dispacher using the scarcely documented
PlayerLoopapi, or 2. you dispatch them with a coroutine later down the line with NextFrame, EndFrame etc, or 3. Make a poormans dispatcher by having awhile(myActionQueue.Count > 0)in Update method
or the ultimate way, use Awaitable<T>
cookies let you use a texture to alter the shape of the light
Like this one for a flashlight
How do I change animation speed preview?
Changing animator layer speed to 0.1 works fine at runtime, but when testing the animation in "animation" it plays really fast.
How do I make it match the runtime speed?
Every time I generate a mesh, it's shape is completely wrong
This is supposed to be 512x512. I've tried my own code, ChatGPT, internet scripts, anything. All of them look like this.
And before you ask, the scale of the object they're attached to is 1 1 1. Changing it to 1 1 5 "fixes" it
Oh you might be hitting the default max vertex count
Which is 65535
512 * 512 is 262144
Change this to 32 on the mesh:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mesh-indexFormat.html
(You should be getting a warning about this in the console)
can someone help me with my code??
What do you need help with?
i dont know what this means
ive been trying to fix it but its not working
this is the code
Is there a way to enable / disable fullscreen render pass features at runtime via a script without changing the actual asset?
I can do this
public FullScreenPassRendererFeature fullScreenPassRendererFeature;
fullScreenPassRendererFeature.SetActive(true);
but when the game ends, it changes the asset in the editor too
That appears to be it. Strangely, the actual script I was using it in, not the one I provided, still doesn't render the full mesh at 200x200. I'll have to do some investigating on that. Any idea how ancient a device has to be to not support that many vertexes?
The example unsupported android GPU that the doc mentions seems to be from like 2011
Ah, then I assume that will not be a problem.
200x200 would fit into 16 bit format though
Yeah, must be creating some extra vertices accidentally somewhere.
can someone help me idt it has anything to do with my code tho
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
yeah that sounds like a physics setup issue, see #💻┃unity-talk
alr alr
how do i fix this issue? on start when i load up my game the main menu scene and the title scene load up at the same time, i have a script for the scene transitions here:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneTransitionScript : MonoBehaviour
{
public List<string> sceneOrder;
private int currentSceneIndex = 0;
void Start()
{
if (sceneOrder.Count > 0)
{
currentSceneIndex = sceneOrder.IndexOf(SceneManager.GetActiveScene().name);
if (currentSceneIndex == -1)
{
currentSceneIndex = 0;
LoadSceneByIndex(currentSceneIndex);
}
}
}
public void LoadNextScene()
{
if (sceneOrder.Count == 0) return;
currentSceneIndex = (currentSceneIndex + 1) % sceneOrder.Count;
LoadSceneByIndex(currentSceneIndex);
}
public void LoadPreviousScene()
{
if (sceneOrder.Count == 0) return;
currentSceneIndex = (currentSceneIndex - 1 + sceneOrder.Count) % sceneOrder.Count;
LoadSceneByIndex(currentSceneIndex);
}
public void LoadSceneByName(string sceneName)
{
if (sceneOrder.Contains(sceneName))
{
SceneManager.LoadScene(sceneName);
}
}
private void LoadSceneByIndex(int index)
{
if (index >= 0 && index < sceneOrder.Count)
{
SceneManager.LoadScene(sceneOrder[index]);
}
}
}
use paste site !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.
ah sorry
so are you gonna fix it or
yeah
📃 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.
https://paste.mod.gg/ !code
A tool for sharing your source code with the world!
📃 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.
ok there
ok stop using the command plz
sorry
you are meant to read it
oh alr
you still sent it wrong.
Paste the code on the site, save and send back generated link
alr
for future reference these go in #💻┃code-beginner
a video on a specific thing you're having issue with rather than someone looking over it ?
well both methods did work for some other stuff before
do ya thing
Oh I thought that would have solved the issue, but it hasn't. They are still that size but they just overlap.
Use a paste site please !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.
Apologies.
Also there's weird gaps in all of the "cubes" except the one at 0 0 but that's a problem for another day.
So is this a completely different/new script? I'm confused
The first script was just a test script. What happened was I got issues with the original script, so I made a test script to see if the issue was with my code or just Unity.
I see you generating 512*512 but still not using 32bit index format
Oh sorry, I override the size in the editor.
Or am I
Oh, that would explain it, would it.
I hardcoded 512 into part of the code, other parts change dynamically.
My bad.
Thx for picking that up!
Well now with it set to 128 and nothing else changed, they're invisible (instead of that horrible purple color). I can select them, and their bounds are visible, but they don't render
Are they just upside down
Looks like your code is adding triangles in counter-clockwise order:cs triangles[triIndex++] = topLeft; triangles[triIndex++] = bottomLeft; triangles[triIndex++] = topRight;
Unity uses clockwise winding order
You are correct, thank you sir!
oh ok thanks
i'm trying to make my game look fancy. i'm new to this. i'm adding some vfx, some camera shake, lighting, and shadows. it's a top down. what other topics should i be looking into?
some "juice" i think i'm meant to call it
this isnt a coding question.
#archived-game-design
... i guess to me, a question about buying shadow asset libraries is more a code question than an issue of game design? but okay, i'll try over there
where is the code question
"should I buy this asset" isn't directly a coding question
In unity 2022 I have attack animations and combos set up.
I need to implement a damaging system. (Melee combat, damageable entities, hp, etc)
I was thinking of creating 2 main components: Damageable and Damaging.
The Damageable component always adds a trigger collider to the object it is attached to.
It also adds HP (hitpoints) to the attached GameObject.
The damaging component listens to OnSwingStart and OnSwingEnd animation events to enable the collider on a weapon. (When the swing starts, the collider is enabled).
When there is a collision between the Damaging collider and the Damageable collider, damage is inflicted.
I really like this system because it's simple to implement, and can lead to interesting emergent properties between systems.
How can i improve this system? What are its drawbacks? Are there better alternatives?
Hi, does anyone by any chance know of a public UnityEvent drawer that enables collapsing of some type? Scripts in inspector can become too long
Rather than enabling/disabling a collider and waiting for callbacks it would probably be better to do a direct physics query such as BoxCast for example
callbacks a pain for animations
You could just use naughtattributes foldout probably? https://dbrizov.github.io/na-docs/attributes/meta_attributes/foldout.html
rather, query is a pain*
I prefer trigger colliders and shaping them to animation frames
one problem though is the trigger information is usually not available till next fixed frame
but trigger colliders have the problem of not giving you contiguous detection
they're limited to discrete collision detection and yes you have the whole timing nightmare, no?
true, I wish rigidbody had like collider.cast like box2d has
yeah you need to wait for physics sim before you get a hit
Thanks for the answer! Performance wise?
Why?
Yes, that should do the work, thanks
I don't think performance is really a primary concern either way tbh
@latent latch Sorry, just saw your explanation
unless we're talking about hundreds of these things
nope, just a player and max 10-15 damageable entities let's say
yeah I would worry more about functionality and clean architecture.
this is interesting actually - you mean resizing/shaping the colliders via the scrubsheet?
like setting BoxCollider.width/height for example?
Okay, good point. Is there really a big change? If I have colliders, I enable the colliders, if I make raycasts I need to start casting rays OnUpdate when the swing starts, up until the swing ends. Is one really better than the other?
Specifically how fighters do it. The'll usually have a 1 frame window for the hitbox
Well think about your code. You enable a collider and then what? YOu need to wait for OnTriggerEnter to run right? That might not be until next frame
With the direct query you write all the code in one spot:
// do the cast
// check the result```
Why would the hitbox only live for 1 frame?
Yeap, does seem less disjointed
full rigidbody detection would be nice for sword slashes, but that could run into detection problems if it's too quick. Depends how rigidbody is feeling, but usually I'm writing that interpolation.
that's my main reason for preferring the immediate query, but I'm sure colliders have other advantages.
fyi you can sub to unity events in code (these get called faster too!)
Yes, thanks. I do some in the inspector to not create code dependencies
well there are other better means like interfaces and in reality its still dependant on that script existing there with a named function
if you rename the func, it just silently breaks! If its via code, compile error!
does anyone know how to access a global texture in a rendergraph renderer feature?
I cannot figure out why the top code logs to the combos list I have, but the lower code doesn’t? The upper code is the DPAD, and the lower are face buttons. The code executes in both, but just doesn’t save to the combos list?
Make sure that logs are not commented during testing. It's worth checking out if the script was saved. You're using else if phrasing, which means the later ifs won't be checked if the earlier ones meet condition. Make sure that all actions are enabled (I think they're disabled by default). Sometimes Unity glitches and code changes don't affect the game - in such cases restarting Unity helps (I haven't got such error in newer Unity versions though).
use your ide's debugger to verify if these are truly being added or not
it may be a pain when debugging input related things but you can add trigger conditions to breakpoints to aid in this
Ok, thanks!
sorry, posted some rubbihs without reading what was actually happening, ignore if you read it 🙂
When using Unity's inbuilt Pooling system, is there a way to specify what is retrieved from the pool, or should I implement multiple pools when pooling objects of multiple (similar) types?
Example, I am currently setting up a setup to spawn Visual Effects based particle systems, for things like blood splatter and dust clouds, using different assets for different types. Should I be using a system that pools all of these "Particle Objects" in one Unity ObjectPool, or a system that makes one pool for each type of Effect-producing object?
I separate the pools cause I find it easier this way, but its up to you how you approach it.
I do have a Generic pooling class I use that has everything i need though
public class ObjectPooling<T> : MonoBehaviour where T : MonoBehaviour
{
public static ObjectPooling<T> Instance { get; private set; }
private IObjectPool<T> objectPool;
public IObjectPool<T> ObjectPool => objectPool;
[SerializeField] private bool collectionCheck = true;
[SerializeField] private T prefab;
[SerializeField] private int defaultCapacity = 20;
[SerializeField] private int maxSize = 100;
[SerializeField] private int amount;
[SerializeField] private int createdAmount;
etc
Has anyone ever had this problem before where stuff looks fuzzy when you zoom into it? (It's not in the video, but that triangle looks normal if you zoom out farther). I'm currently testing out Unity 6, and I was trying to make a basic mesh generator, but I can't figure out this problem, and it looks really ugly.
i believe it might have something to do with scaling i had a similar effect on a mesh i had before
Do you have any recommendations for how to fix it?
im not familiar with mesh generators really but did you assing the uvs?
Oh that could be it. I forgot how to properly generate uvs. I'll google a tutorial on that, thank you.
Huh, I don't think it worked.
It's confusing me so much, because it just looks like random noise, and to my knowledge, I don't have any sort of post-processing or global illumination turned on.
- Try creating lighting settings(press "new" button). You don't have any assigned ATM.
Also, this has nothing to do with code. Next time post in #archived-code-general or some other relevant channel.
Yeah, that didn't change anything. Thanks for the suggestion though. Also I know it's not really code related. I wasn't sure if it was somehow connected to the mesh generation stuff since the non-generated meshes are working fine, so I figured I'd do it in here in case someone had had a similar problem with mesh generation (also because other channels don't seem to get answered), but I'll relocate in future.
It's unlikely related to code generation. Doesn't it happen with the capulsule as well? You're talking about noisy surface right?
Or is it just the video quality?
Oh I'm stupid. I was missing this little line of code.
Then I didn't get what the problem was I guess.
idk why that fixed it, but it did, so I'm not going to question it too much. It does happen slightly when zooming into the bottom of the capsule, but you shouldn't be doing that in game anyways, so I think this'll work. Thanks for the help!
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
I don't know if you care, but it was happening again with some other faces, and I finally remember what's causing it, so I figured I'd share for anyone curious. I forgot that normals are connected to the individual vertices instead of the faces, so if you have 2 faces sharing at a sharp corner, you ideally want to duplicate the vertex for each face, so that it can have all of its vertices' normals pointing in the same direction as the face to prevent weird lighting shenanigans.
ok so i know this isnt necessarily unity's fault (or i dont believe it to be)
but is there a way to prevent visual studio from randomly automatically adding lines of code to my scripts?
was wondering why my game wasn't building
and it said a script i made was trying to use some things that i never asked it to use at all
me, obviously never put it in the first place realized visual studio's intellisence may have done this
i like the suggestions, but i dont want them to automatically do stuff behind my back
what do you mean
as in the usings?
ah yeah, actually yeah that seems to be the main thing happening
its what happens when you accept (intentionally or unintentionally) an ide auto complete recomendation that would require said using
ah, i need to find out how to turn that off
anyone have any tips for cleaning up Physics2d.Collider2d.DestroyShapes? I am loading a scene and destroying existing colliders is taking minutes to execute (there are ~20,000 of them)
they arent simulating, half are used for static collision half are click colliders
try cleaner code:
Dictionary<MyAction, string> actionToComboMap = new();
void Awake() {
actionToComboMap.Add(LeftAction, "Left");
actionToComboMap.Add(RightAction, "Right");
// ...
}
void Update() {
foreach (var (action, comboName) in actionToComboMap) {
if (!action.WasPressedThisFrame()) { continue; }
Debug.Log($"{comboName} was pressed");
combos.Add(comboName);
time = 0.35f;
break;
}
}
... and even cleaner would be if each action contained the combo name and maybe even activation logic:
List<MyAction> actions;
void Awake() {
actions = new List<MyAction>() { LeftAction, RightAction, ... };
}
void Update() {
foreach (var action in actions) {
if (action.WasPressedThisFrame()) {
action.OnPressed(combos, out time);
break;
}
}
}
but your issue likely comes from the fact that each action breaks. So if LeftAction activates, the other actions won't even be checked.
proly just Try pattern,
//LOOP
if(action.TryWasPressedThisFrame(out var OnPressed))
{
var time = OnPressed(combo);
}
well might as if (action.TryPress(out time)) { break; }
FYI, you might wanna call RecalculateTangents also. This is needed if the shader uses normal maps, for example. Otherwise you get more weird artifacts
I am looking at making a little battle game in unity, where you control circles that serve as divisions/batallions. My only problem is drawing frontlines. How would I go about drawing a dynamic frontline in unity 2d where the line would adjust to units moving around, split up into encirclements and all that? I thought about using line renderers, but I have no idea how I would go about doing this. Any suggestions?
Explaining in detail what a "Frontline" is would be a good start.
Frontline would be a line that shows the border of the two players in a battle, the frontline would need to more around and adjust with the units and battle, as well as possibly splitting up at times in case encirclements form.
Maybe you want a convex hull?
https://www.geeksforgeeks.org/convex-hull-algorithm/
Looks promising, thank you
Guys what do you think the maximum AI’s ability is for coding in Unity right now? Like, what functionalities would it be able to code (eg. a multiplayer 2d game, an endless 3d runner etc)?
Guys, what's better to do with killed enemies that don't respawn? Destroy() or disable them?
Why would you keep it around if you don't need it anymore?
Ok, got it, thanks
It can solve most of simple problems. It can solve a huge amount of common problems. It struggles with some difficult problems. It's almost incapable of inventing new things. Pretty much the less common problem is, the higher is the chance it will give you insufficient, wrong or misleading answers.
In most cases (probably 95% of games) it's better to get rid of them. In some cases you might want to use pooling - hide them and use in a different place if needed (just because they don't respawn, it doesn't necessarily mean such enemy won't be spawned in another place). Some games might occasionally want to keep dead units on the scene for some extra interactions (e.g. looting or necromancy) or keep only a small piece of information (e.g. location of their death and who they belonged to).
It's easy to use the unity ObjectPool<> to set this up
i know. i know how to read the docs lol
nope, it's just straight up not there. someone did not finish their sentence
ellipses use 3 periods
i just thought it was funny lmao
i know, i mean the message was cut off leaving ellipses, then the ellipses got cut off due to the hover box size
Yeah that's what I thought initially but
damn
I'm guessing the documentation in code is auto generated and what happened is it tried to find a link to a class called "mesh filter", but couldn't, since that hyperlink just leads to a manual page
so it just ended up omitting "mesh filter" entirely lmao
Hey I'm trying to create items with ECS and until now I've used Scriptable objects is there a way I could use it with ECS?
probably ask in the #1062393052863414313 channel where the ecs people hang out
lol ok thx
So, I kinda made my 2D character controller that can stick to surfaces a bit too good, as it can stick to any surface, but i want it to detach and move off of the ground
{
overlapped = Physics2D.OverlapCircle(groundCheckPos.position, groundCheckRadius, level);
RaycastHit2D hit1 = castRay(rb.position, -transform.up, slopeCheckLength1, Color.red);
rayed = hit1;
grounded = rayed && overlapped;
if (grounded)
{
getGroundValues(hit1);
}
else resetGround();
doSlopeCalc = Mathf.Abs(slopeDownAngle1) >= minSlopeAngle;
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, -slopeDownAngle1), timeOfRotation);
}```
what's the best ide for unity?
also whether it does consume lots of ram or not
{
if (ceilinged)
{
velocity.y = 0f;
}
if (!grounded)
{
velocity.y = Mathf.Max(maxFallingSpeed, velocity.y + delta * physicsMultiplier * playerGravityForce);
isJumping = velocity.y > 0f;
isFalling = !isJumping;
return;
}
isFalling = isJumping = false;
velocity.y = slopeDownAngle1 != 0 ? groundSpeed * -slopeNormalPerp.y : 0;
rb.position = slopeHitPoint + (Vector2)transform.up * posOffset;
}```
you have 3 options for supported ones, Rider which is only free for non-commercial use, Visual Studio, and VS Code (which isn't even an IDE, it is a text editor with plugins that make it function similar to an IDE). that order is also from best to worst
thx!!!! I much appreciate your help!!
I have a problem: I have an animation for an attack with a sword, but the animation only plays for one frame instead of the full animation. Is it because I'm doing this in Update()? (I'm using Unity C#)
Are you restarting the animation every frame? That would be why yes
No, pay attention to your if statements, you're not doing it every frame.
Start debugging your code with Debug.Log and the Animator window
What's the difference between:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.ComputePenetration.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider.ClosestPoint.html
Looking for the best way to get a contact point using a trigger collider and I know int he past that closest point was far from accurate
I guess a better question would be what's the best way to get contact points from a skinmesh render bone against a unity collider
hey does someone know why my camera Changes when im throwing my Item and why I cant pick it up ?
PlayerInventory:
https://pastecord.com/bymasyfoci.cs
ClosestPoint will return the same point you passed in if it's inside the Collider
It won't really tell you the penetration at all
Nothing in this script would directly move the camera so it's probably a script or component attached to one of the GameObjects you are instantiating or activating
yea I found out why with the camera.
What does [ExcludeFromDocs] do exactly?
An attribute. Probably does what it says. Aside from that it doesn't seem like unity wants us to know.
Right, I'm trying to take a peek at the Quaternion.LookRotation method to see how the math behind it works, but I can't find where it is
It's probably implemented on the C++ side, so we don't have the source code
But it should be pretty plain and similar to what other engines do
yep, that method is implemented in c++, not in the c# bindings
https://github.com/Unity-Technologies/UnityCsReference/blob/b1cf2a8251cce56190f455419eaa5513d5c8f609/Runtime/Export/Math/Math.bindings.cs#L98
What approach is advisable for setting an Observer Pattern scripts observed class dynamically? For example, I have a Health class, and a HealthBarUI class. The Health class calls an Action when the health value is changed, and the HealthBarUI class observes this action and adjusts the UI element accordingly. This is working correctly.
However, this requires a reference to the specific Health instance on the player, as this Health class is intended to be re-used on any object that has health, including enemies and breakable environment objects. Would this be set as part of a game management class also in charge of spawning the player object?
Not an expert, but I'd make it an interface
Probably a wrong way to do it, but it's how I'd do it
I just assume that having a lot of calls in awake or start all take place for that kind of function on the player is generally not advisable because maybe there is a different, better way to do it
Wait, how many destructible objects to you plan on having in a single scene?
Not a whole lot, but I would like to keep my performance budget low to include low end devices
More than 10 but less than 100 on screen at any given time
I mean, if all you're doing is changing a float variable, I don't think it's going to be that big of a deal
Well the player HP bar is not the only reference I need to be setting or calling, it was only an example. If I had 100 health instances(including 1 player), I dont want to loop through them all to find the one on the player if I dont have to
I also thought that the player spawn could call an action, with a reference to the player object, but then the HealthBarUI would also need to subscribe to that action as well, and I am having trouble with determining how to approach setting which class is observed since the objects are not pre-spawned in at scene load so setting the reference in the editor directly wouldnt work
You could use a method to find a gameobject with a specific name, or tag, and then search for its health bar class component, then call the method for decreasing health.
Yeah but if I have a lot of classes that need references to different classes on the player, using Find would cause a spike for all of that
This class is placed on a UI element, not the player
Again, this is only a single class, but if other UI elements and other scripts need to also observe the player Health instance, using Find every time seems like not the right call to me
Hmmmm... I'm not too sure, but if instead of finding by name, you find it by tag? If say there is only one tag called Player, it's faster and more optimized than finding by name
Does the player change?
Like, is it destroyed at some point in the game?
It does not change but the instance would sometimes be destroyed and instantiated, yes
As the game has multiple playable characters, each is a separate prefab
This is where my idea of an Action in the spawn logic came from, but then every object in the scene that needs it would have to observe that class as well
Okay, the idea I have is, instead of destroying the characters, why don't you just pool them? You deactivate them and then the data is still in cache, that way you don't have to find the players all the time, only once when they appear
Well this still doesnt really solve the problem because the observed class is still not set
I appreciate your help though
I'm not sure how to solve that issue though, other than telling you searching by tag is better for large amounts of objects
I guess I should just do it the way that makes it work first and then worry about it later if it causes a problem
You should have a higher level manager that have access both to ui and the player(or any other object that has health), orchestrate the initialization of the relevant objects and passing references around.
is there a search term to find all missing script in a scene?
https://web.archive.org/web/20130514114424/http://wiki.unity3d.com/index.php/FindMissingScripts nope but u can make u an editor script that does it
nice, thanks
`using StarterAssets;
using UnityEngine;
using UnityEngine.Playables;
public class CharacterSwapper : MonoBehaviour
{
public GameObject char1;
public GameObject char2;
private GameObject activeCharacter;
private bool playerState;
void Start()
{
activeCharacter = char1;
char1.SetActive(true);
char2.SetActive(false);
}
void Update()
{
playerState = activeCharacter.GetComponent<StarterAssetsInputs>().swapCharacter;
if (playerState) // Check for input
{
activeCharacter.GetComponent<StarterAssetsInputs>().swapCharacter = false;
SwapCharacter();
}
}
void SwapCharacter()
{
Vector3 position = activeCharacter.transform.position;
Quaternion rotation = activeCharacter.transform.rotation;
activeCharacter.SetActive(false);
activeCharacter = (activeCharacter == char1) ? char2 : char1;
activeCharacter.transform.SetPositionAndRotation(position, rotation);
activeCharacter.SetActive(true);
}
}
`
I'm attempting to make this darn code swap between two charaters. This code is stored on an empty object, and char1 and char2 are the characters i wish to swap between. However, "playerState = activeCharacter.GetComponent<StarterAssetsInputs>().swapCharacter;" is not working. Does anyone know why it won't take the bool, and instead returns "NullReferenceException: Object reference not set to an instance of an object
CharacterSwapper.Update () (at Assets/Scripts/CharacterSwapper.cs:21)"
It’s failing to get that component
how can i fix that
That object needs to have that component
I need to give the empty object the StarterAssetsInputs script?
activeCharacter.GetComponent<StarterAssetsInputs>().swapCharacter;
right here, i'm referencing the activeCharacter, and grabbing the bool from the other object. Why isn't this sufficient for the code?
becuase
either activeCharacter is null or activeCharacter doesn’t have a StarterAssetsInputs component
While youre there
You should have references to these components saved
Rather than getting them every frame on update
how would I make that change
on phone so a little tricky but like how you have your gameobject fields at the top you can have a field for each StarterAssetsInput and either set them drag and drop style like your gameobjects or set them by doing that kind of getcomponent in start
okay thanks
Shoud .meta files be source-controlled?
Yes
If you're using git, there is already a premade unity git ignore
i need waveform for some project
decided to use line renderer, and bake it into mesh
but im concerned about the verticles/triagles count
is there any other way to have runtime waveform?
good god 7M, can you not sample at a lower rate for this mesh?
Could also make/update a texture instead with a compute shader
can i get sample data with lower rate? i still need audio to be good
about texture, not sure how to do that..
depends how you are getting this wave form. instead of using every single sample, you can use say every 4th. Having a vert for each one is clearly not going to fly.
hmm, let me try
I think a compute shader could work by giving it a block of samples and you can have each compute thread produce a column of pixels for the sample
if i only knew anything about shaders
try sampling at a much lower rate first and see how it looks. If it doesn't yield good results you can perhaps change it to get the average of a range of samples instead
used 4, 8, 16
the 16 cuts it to 449k verticles
much better but still a lot
and i imagine what would happen with much longer audio
are you ever going to be able to see 449k verts at once? unless you're getting really close to this thing, maybe you can sample a number of times proportional to the size on screen?
i guess id better off writing custom mesh gen for that 💀
no, maybe i could cut it into pieces?
We came to the conclusion it's most likely due to the asset having it's own asmdef, any way to get around this?
You can create an Assembly Definition Reference and reference Unity.Timeline.asmdef. That will let you add your own code to that assembly.
Will try that, thanks.
Just remember that this is a hack, and Unity could change TrackAsset to not be partial anymore, in which case this won't work anymore. Assembly Definition References are not really intended for this, it just happens to work with Unity packages as well.
Additional question, is there a way to make these properties show up in the inspector?
https://github.com/needle-mirror/com.unity.timeline/blob/master/Editor/Activation/ActivationTrackInspector.cs
Hello guys ! I'm trying to make something really simple :
- Have a VideoPlayer that takes an URL to my remote server that hosts a video
- Play the video
But I'm getting this error :
WindowsVideoMedia error 0x80004004 while reading <myURL>
Context: IMFSourceReader::WaitForSample in StepAllStreams
Error details: Op볡tion abandonn맍
The video file seems fine since it works if I put it directly in Unity.
The weird thing is that it sometimes work, sometimes doesn't...
Any ideas what could be the root cause ? Or how to solve this ?
please @ me if you are able to help, I have no clue what to do
Hi guys, I am just wondering if I can get an input from somebody about my code. I have got an AI character which should be checking with a linecast to see if the player is in line of sight, and if the player does come within the line of sight of the AI it should start to move towards the player. however it doesnt seem to recognise that my player is there and doesn't want to find it
does your player have a collider?
yes
have you checked whether the cast is hitting?
it isnt no.
have you debugged where the line actually is?
I have a debug.drawline which isnt drawing the line
make sure you're looking in scene view
it should draw from the ai character torso to the player torso but it doesnt
it doesnt show in scene view
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
its the FindATargetVIALineOfSight part. the rest works fine if I drag the player into the lock on myself
don't put your debug line inside the if
and add extra logs to check if that point is being reached
I added some debugs to see what isnt getting reached and it appears that from the CanIDamageThisTarget if statement and below isnt executing
but I think thats due to the fact that the ai isnt finding my character with the Physics.OverlapSphere
i guess verify that the layers are correct. Id say use a debugger + move the retrieval of the layers to be seperate so you can inspect it easier
I did that earlier and found that it is detecting all of the different parts for the character but it isnt actually detecting the player prefab
like it will find the torso and the head colliders and whatnot
but isnt finding the player one
and I have tried to do a GetComponentInParent which didn't affect anything
If it overlaps many colliders... then it will return them all as results.
so either adjust layers to better filter out other colliders or verify why get component in parent did not work (perhaps the hit collider is not on the correct object at all)?
I have just changed it so the debug prints out the parents name and it is detecting itself and the player but it isnt setting the player as the current target.
use a debugger so you can inspect better
You can use collider.attachedRigidbody to quickly get the rigidbody object, which i assume would be your player's root
Alternatively, have a component on the bodyparts that have a reference to the player
I'm trying to figure out how I'd generate the map for my dungeon, on the left is what the in-game map would look like. On the right, I've simplified it down to a tree-like design. It feels like it shouldnt be that hard to generate something like that tree, but I dont really know where to start.
If I write it down as text, I get something like this
G1
G2
G3 -> R1
G4 R2
R3 -> B1
R4 B2
B3```I dont know if thats actually helpful to figure out the generation, but its as far as I've got. Any thoughts?
Would it be grid based?
does that matter? surely if I'm creating a tree/graph, that wouldnt actually care about the location of each node
Doesn't really matter tbh
What I like to do is run a "physics" simulation on the graph
Each node can have a radius and some connections
And then you iteratively try to relax the graph
By separating them circles
yeah, I'd do a force directed graph once its built
Not the best example but something like this
https://www.youtube.com/watch?v=NpS5v_Tg4Bw
If the map doesn't have cycles then it's a lot easier
I'd process it do actually produce the more aesthetically pleasing version of it, but thatd be a second stage
based off the rules I have with the dungeon itself, the more complex map on the left can be represented as the graph on the right
I lead with a simpler map as its easier to think about
something I should mention is the dungeon itself isnt 1 scene with all the rooms stored inside it that you move through, its more like a single scene for the room. Moving to the next room just reloads the scene with the new room info
Yeah I see. Not a problem
I prefer to do procedural generation stuff purely with POCOs anyway, no gameobjects involved until everything is ready and the objects need to be spawned
to quickly illustrate the way it works if its not clear, you must always travel in the direction of a boss, so even though the graph shows 3 different red-boss locations, they're actually just the same room
hey there, I want to make a text editor in unity similar to how notion works. Can I get some suggestions on how I could do that? I feel just a big inputField wouldn't quite do the job...
it's part of a bigger app that stores the written text in my database via my api, but I didn't think about needing a text editor
look at the UI toolkit to start cus that will be way better vs ugui
is that a package from the unity asset store?
newer UI system thats similar to html and css in terms of elements and layout styling
that's great. I'll look into it!
I'd probably do game objects if I was going to do a traditional dungeon, a while back I saw a very clever thing where somebody generated a bunch of rigidbody boxes and unity automatically relaxed their distances. quite similar to the FDG approach in that video
honestly it would be so much easier if I my dungeon was going to be like that 😆
alas
so how could I generate the map like this?
Im not really sure what format to store it in
Which stage is this exactly?
Just the layout?
I use a node graph (looks similiar to shader graph etc.) that defines the nodes that are allowed and what can be connected to what. I call it the layout source graph
I then toss it into a generator that makes sense of it and tries to place all the needed rooms while keeping them at certain separation distances and respecting other rules i have set up in some [SerializeReference] lists on the nodes
this would be the first stage
So it's sort of abstract
Does this part need to be generated or does the developer define it?
(I don't really know what you are actually asking about)
so the metro map here is the final thing I want, but in an abstract way, its nothing more than 3 lines that connect at an intersection. I basically want to figure out how I'd create the 3 lines, see how they intersect, and convert that into a usable graph
hey so im makinga multiplayer game but whenever i kill a player this error pops up
can someone help me?
What sounds right is I draw a line, and that line MUST overlap at least 1 other line, then one side of the line after its intersection is found gets removed, then I draw the next line. Which would do this
Generate a line
Pick a random point along that line
Generate another line on the random point
Repeat
Make a simple graph data structure to start with
With nodes and edges
This is what I imagined when seeing your prev example
And like a helper method that splits an edge into two
Are you destroying a networked gameObject with Destroy() instead of instead of calling Runner.Despawn()?
This is a #archived-networking problem so it may be better to move it there, though the error suggests you may be trying to use Destroy on a networked object instead of PhotonNetwork.Destroy or your calling the network destroy on a object that does not have a PhotonView/invalid ID
yeah I noticed a lot of the maps do a tree shape like this
Destroy
!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.
I guess its simple, you have a branch and you produce a new branch half way in some dir that alternates each time.
Not sure how you could produce something like this with a branching tree
You shouldn't call Destroy() for networked gameObjects, you have to call Runner.Despawn() on the server (if you're using Fusion, for Pun you should use PhotonNetwork.Destroy() instead)
im like a beginner im sorry i dont know what that means heres my code though
A tool for sharing your source code with the world!
Is the error message the same in Fusion? Ive only seen that specific one in PUN's framework
I'm gonna say it. You shouldn't be making networked games yet
i am using PhotonNetwork.Destroy()
study their docs before anything
it is a new way of structuring you have to adhere to at least for fusion 2 what im using it took a while to understand
PUN also has sample projects and a discord as well, but I agree, multiplayer games is very difficult to make as a beginner, even difficult for experienced devs, so it could be a big undertaking to start with imo
i understand that but ive been trying to fix it for a while now and this is the only thing im stuck on everything else has been working perfectly
i'll find my notes, but I managed to come up with a rule for a map like that where 3 colors share a single node, and it seemed like the solution
it might be that one, but if you copy a branch over to another side of the tree and change a color, it works
If its something you really want to learn, go for it, though after making 2 multiplayer games myself, I can say that this will likely not be the last problem youll run into, you may end up refactoring your code several times, and if you plan on releasing/publishing, there are also other considerations (and a subscription cost)
there must only be 1 line per color, so the red meets yellow twice (at 1 and 2). the right hand side is what the basic graph would look like, and the middle is what I'd need to intepret it as
yeah ive run into a couple problems but those were straightforward im just not able to figure this one out
Fair enough, I would try to isolate the problem, make a new script and compare it to the docs, try PUNs sample projects that already handle destroy, see if you can get it working then compare the difference, or try adding some Debug.Logs and breakpoints and try to see whats happening frame-by-frame, and make sure the object your trying to destroy has a PhotonView properly setup on it - also make sure the object your trying to destroy has an owner (IE: was instantiated with PhotonNetwork as well)
I have hundreds if not thousands of pngs (animation frames) that I need to apply normal maps to in the unity sprite editor. Is there no way to apply them automatically, or mass assign?
I've attempted asking AI and they keep trying to make an Editor script for it, but they haven't been working. Is it possible to make it work?
apply where? In an animation clip?
No, apply _NormalMap as secondary texture in the sprite editor.
Ah right, are you trying to use the texture importer then?
No, so far the only way I know how to do it, is to click on each image individually, open the sprite editor and add a new secondary texture, input _NormalMap and selecting the normalmap, and then hit apply. Repeat. That will take hours, so I want to know if there's a way to automate it.
Like, so for example "tree1.png" will automatically get "tree1 normal.png" assigned as a normalmap to it.
You can get a TextureImporter for the asset or assets and set the secondary texture array to what you wish:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/TextureImporter-secondarySpriteTextures.html
so make some static function and use [MenuItem] to call it in editor
if you want to automate it even better you can use UnityEditor.Selection to do this over many assets you select in the project window
is there any way to do something like [DoNotSerialize], so if I was to write public int DefaultRoomWidth = 50; it will show 50 in the inspector and I can change the value in the inspector, but if I ever alter the value in the script, unity will update the inspector to match the change?
its annoying that once its set in the inspector, theres no way to get unity to read a new value that i explicitly set in my script
well you cant have a serialized value AND it also use the default set in the class?
If you dont want to serialize it, use [NonSerialized]
a value set in the script is treated as the default
the inspector value is the serialized, instantiated value
the inspector value takes precedence
which stops it appearing in the inspector
indeed it does
I still want it to show up there, but if I alter the code then that change should take priority
then use something like naughty attributes (which can show extra "read only" values easily) or create a custom inspector editor
It really means "save the data", but unity also shows serialized data by default
So they get used sort of interchangeably for saving and also showing in the inspector which is a bit misleading
so why does unity not have something that detects whenpublic int DefaultRoomWidth = 50; changes to public int DefaultRoomWidth = 250; and overwrites the serialized value?
Because you could lose work
it would be way more annoying if it wiped out all your changes in existing assets
I managed to work it out, thanks a lot!
only if it overwrites all inspector values every time you save, im talking about if I change a single property, i want that one to update
ok, what if you change multiple properties
wait sorry brainfart
what if you have multiple independantly configured instances of a given script
for example in prefabs or prefab variants
i see your point!
and there's no observable difference between a value that's just the default and a value that's been tuned and happens to be the default
like maybe you set the default speed to 0 just as a placeholder, and in one instance you explicitly want it to not move, if you change the default with the behavior you're proposing, it'd make that single instance suddenly be able to move
what you're proposing isn't useless, it'd just cause more problems than it solves, unfortunately
that is, if it were unity implementing it editor-wide
if you wanna just see the value in inspector, click the 3 dots and swap it to debug mode. itll display everything so you probably wont have it on forever
or custom inspector
if you have a specific usecase where it does make sense and doesn't have these kinds of drawbacks, then it'd make sense to make an editor script or something
ehhh seems like debug mode causes a lot of problems... would not recommend that
I dont see it
not on the component, on the inspector tab itself
What problems?
ooh, the inspector
ive seen quite a few people having issues here where the issue was just that they had debug mode on
btw you can right click the script and HIt Properties and you can Debug view only that popped out window so it doesnt touch the original inspector 
or was that a different thing 🤔
i wonder if I do something generally wrong with using unity, like I rely a lot on code and not too much on the inspector
Pretty sure that's a non-issue, just turn it off when you need the normal inspector again
I mean it's an issue if you are so new that you don't realize that it's in debug mode
Which i have seen, yeah
But that's user error
yeah you should use the inspector for config and stuff
if you edit everything in code you'll have to recompile just for tweaking values
pop out the inspector for specific script you don't have to touch the original inspector
some things dont need to be instance variables but some do. Id say it varies. If something can be static or const then i will use that.
needs to be shared by many instances? scriptable object!
unity is designed around doing a lot in the inspector. Though sometimes people try to set up too much from the inspector rather than doing it in code. It's really just a matter of whats easier for making the game
Been recently trimming off a lot of static fields (like lists i reuse for procedural generation) after I started multithreading
And just pass around pre-allocated collections instead
Though I gotta see if I could still use static fields and lock 🤔
something im trying to do more of is getting a scene in a state where most things are already configured and ready to go, too many times ive just constructed and configured loads of stuff in awake, like finding references to objects, when its far easier to just drag and drop to the fields instead
ofc DI is always better than doing a GetComponent at runtime
You can also add default references to a Monobehaviour if you select the script file
I recently heard that it works for non-monobehaviour stuff too, in unity 6 👀
how does that work?
that only works for newly made components in edit mode and well cant be instances in a scene
It's because these object references can't really have default value from code
Ive heard people mention zenject a lot, but DI isnt something I've played around much with
I mean, I do DI a lot but thats mostly just normal OOP design
doing DI the manual way is a pretty good idea anyway, the frameworks just automate some of the repetitive stuff
ive struggled to find an example that actually explains it in a way that sounds useful
the theory of it, I understand
all the examples feel too daunting or "why would I need to use a DI library for that"
it's most helpful on larger projects with a lot of interconnected systems, especially if you want to write any unit tests
by the way just using the Inspector is a form of DI
I make do manually providing required dependencies but sometimes its just easier having a system that "distributes" them for you
i expect most big projects dont only use monobehaviours so it fills that gap
You dont really need a library for that , but it helps.
most .net frameworks have their own systems already built in by MS , unity is a bit different cause it doesnt really expose a "main entry" program.cs
i mixed up library and framework, i just meant something like zenject
most of this doesnt mean anything to me, (ive never heard of auto-mocking), which probably means its not of any use. But surely there must be something to it that could help me out
personally done all other DI in .net but in unity I never really needed such a custom system
but also Im a solo dev and most of my projects have been small
its pretty easy to make a basic system by creating a simple Bootstrapper object
atm I'm trying to ditch the way I was doing rooms in my dungeon, in hindsight it shouldnt have been done the way it is
What way are you currently doing it
zenject in particular is pretty bloated haha, in projects where i've used it i've ignored 99% of the features
Load the dungeon scene, generate an array of RoomLayout (just a struct with dimensions and settings for a room). I pop the first item from the array, and the room gets built using it. Then once you move to the next room, I pop the next layout and reload the entire dungeon scene again, (only this time the map exists so it wont generate a new array)
it felt like a good idea at first
I think once I get the actual terrain generation for the room in a state thats not a bunch of placeholders, it should make it easier to correct my past mistakes
I have a question about model clipping, is this the right channel?
Like clipping in the camera?
Or polygon clipping/computational geometry?
Is there a nice built-in type to select a single layer in inspector in unity, that I can then easily assign to gameObject.layer?
LayerMask allows multiple selection and is a bitmask
so not easily convertable
use LayerMask then do a bitmask shift
just dont put 2 layers or it will break
yea but that is not the ideal solution isn't it
goddamnit why isn't there a proper way
well its the closest imo
I guess if you enjoy strings you can use that...NameToLayer
EditorGUILayout.LayerField does it but I don't know if there's an attribute that makes an integer draw with it
not type safe tho
strings are even worse than a bitmask
how tf does unity not have an attribute like that built in is beyond me
i have been doing this for ages works for me
Bit odd yeah
yeah it works just fine, as long as you know not to slap 2 layermasks
You could make a property drawer for it
Found this but it's for entities (?)
https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.LayerFieldAttribute.html
just gonna leave this here incase you want to look into it
https://discussions.unity.com/t/get-the-layernumber-from-a-layermask/462678/3
I've seen it but thanks
I'm just devastated that this is still an issue in unity
I guess. Layers and LayerMasks are different though so it makes sense
Original question didn't have anything to do with layermasks though
There should definitely be a property attribute for drawing an integer as a layer dropdown
i guess, but as of now, the layermasks just makes it easier to have all the layers in a dropdown already
i need help with my code, the code is maked by me i tested it but it doesn't normally work. now i need help from nice C# unity programers to make it working. This is a code of raft spawning (i am making game like raft but more realistic). This is a hard question for me, i am 4 days thinking and relizing how i can make normal raft spawning script but still not normally work.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
all nice working on main raft but when i walk example forward
@wintry crescent ```cs
public class LayerAttribute : PropertyAttribute { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(LayerAttribute))]
public class LayerPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
property.intValue = EditorGUI.LayerField(position, label, property.intValue);
}
}
#endif
Just add ``[Layer]`` on your int field to use it
thanks <3
I'll need it too so thought I might as well make one 😁
I will be glad if you help
https://github.com/dbrizov/NaughtyAttributes Naughty attributes has a layer drawer attribute
pretty sure there are a few other packages like this that have it too
That apparently supports string fields
Not sure why they do all this custom stuff instead of just using LayerField
https://github.com/dbrizov/NaughtyAttributes/blob/a97aa9b3b416e4c9122ea1be1a1b93b1169b0cd3/Assets/NaughtyAttributes/Scripts/Editor/PropertyDrawers/LayerPropertyDrawer.cs
I'm using EditorAttributes, which is allegedly better, and yet it doesn't have that one 🙃
Ha yea there are too many variants of this kinda thing
it has other cool things though, for what it's worth
the fact unity doesn't have a layer type built-in is a disgrace after so many years
I remember struggling with it in my first projects in unity 5
Osmal can you help me?
Looks like it doesn't have the "Add Layer..." button that the native layerfield has
In the bottom of the dropdown list
huh guess they did a custom one?
Yeah they dont use layerfield at all for some reason
I thought maybe it didn't exist back then, but it's been a thing for a long while
maybe for string and int support
I am currently looking into downsampling the depth texture into a texture with mip maps enabled. so to generate a depth texture where each mip is a downsampled version of the previous mip. I notice you can't read from one mip and write to a different mip at the same time, is that correct?
bump
I tried overriding the OnInspectorGUI but that didn't work, any other ideas?
https://pastebin.com/MDERtikj
please @ me if you are able to help
Maybe you can write your own custom editor that overrides that ActivationTrackInspector?
This is for #↕️┃editor-extensions
yes, that is certainly an option, I was just wondering if it was possible to somehow make it show up in the inspector to make the workflow a bit more intuitive
but so far, it looks like I'll have to go with the custom inspector
can anyone tell my why my player shows up perfectly fine before respawning, but after respawn the player's sprite disappears in game? it still shows in the scene tab, but in the game tab it only shows the background, platforms, and the point light that is attached to the player. i set the respawn point's z position to 0, is it supposed to be in front of the scene? the project is a 2d platformer if that's of any use.
here's my respawn script:
public class Respawn : MonoBehaviour
{
public GameObject player;
public Transform respawnpoint;
public Camera view;
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player"))
{
player.transform.position = respawnpoint.position;
view.transform.position = player.transform.position;
}
}
}
your camera is too close to the player on the Z axis so it cannot render it.
obligatory: use cinemachine to control the camera
thank you!
im trying to use my microphone but whenever i click play it is SO bitcrushed?
`` void microphoneToAudioClip()
{
string microphoneName = Microphone.devices[input];
microphoneClip = Microphone.Start(microphoneName, true, 20, AudioSettings.outputSampleRate);
_audio.clip = microphoneClip;
_audio.loop = true;
_audio.Play();
}
``
idk how to fix it can anyone help?
do you know what the sample rate was for those past attempts?
is that in the project settings?
I think so but if you have an audio file from a recording then you can see on that
Try putting the sample rate as an int manually such as 44100 for 44khz
if 44k is bad then something else is wrong
what else could be wrong?
as the docs say, did you check the sample rates supported by the microphone device?
what's the best way to setup a two-character system (like genshin or hsr)
should I have two meshes with animations and render them based on which one is being requested?
if you have an output audio file plz check that to see what its bitrate and sample rate is...
ok let me figure out how to get one rq
you should be able to get these details from the audio clip too so you can log em all out
Hello, is it possible to move the cursor position through code on webGL? It seems like Mouse.WarpCursorPosition works fine on desktop platforms but not on webGL.
I presume no web browser allows a page to manipulate the cursor so you may need your own virtual cursor
So would locking the mouse cursor and making a fake cursor be the simplest solution?
I think for supporting web yes, unless you can find something allowing cursor control in a html canvas
Ok, thanks
Use virtual mouse
Hey all, I'm having a little trouble figuring out how to add renderers LOD Group from script. I'm working on a modular character where the base mesh is using 4 LODs. I'd like to add my clothing to each of these LODs.
var renderers = clothingLodGroup.GetLODs()[i].renderers;
// Combine the current renderers with the new renderers
var combinedRenderers = new List<Renderer>(baseLODs[i].renderers);
combinedRenderers.AddRange(renderers);
// Assign the combined list back to the LOD
baseLODs[i].renderers = combinedRenderers.ToArray();
I have this, looping through all the LODs, combining the renderers to one array and inserting the new array back in. But this does not seem to do anything.
GetLODs() is probably returning a copy of the LOD array
hold a ref to it, modify the ref, assign it back
That was it, thank you
Let's say I have an item that can cycle between 10 different sprites depending on the state of the item. How would you go about setting up the swapping between the sprites? Surely not 10 different slots in the inspector. Maybe a Scriptable Object to hold them?
hey can anyone help me figure out why my jump animation is bugging out, the jump is jumping really quickly and then is already playing the idle or running animation.
https://streamable.com/ue7vi7
https://paste.mod.gg/csxwfkvvomeo/0 playermovement script
A tool for sharing your source code with the world!
I think it would help a lot to find your error if you cleaned up your code, all those else if else and explicit angle settings are surely redundant..
Is it a code or animation issue? Do you see it transitioning from jump to idle state quickly?
i figured out the issue
it was just becuase that i accidently connected a few wrong
animations
i thought it was a code problem
You might wanna make use of Blending Trees -- you're duplicating states right now (like Idle/Falling_Idle and Running/Running_Backward)
i have no clue how to use blendtrees lol
i should probably learn it
also
but also my character is
clipping through my camera
!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.
hi im having a hard time finding unity 2d frustum culling on youtube
i got this very rough script that i think needed heavy improvement but dont know where to start
using UnityEngine;
public class FrustumCulling : MonoBehaviour
{
[SerializeField] private Camera playerCamera;
[SerializeField] private GameObject[] CullingObjectsParent;
void FixedUpdate()
{
float cameraHalfWidth = playerCamera.orthographicSize * ((float)Screen.width / (float)Screen.height);
float cameraRight = playerCamera.transform.position.x + cameraHalfWidth;
float cameraLeft = playerCamera.transform.position.x - cameraHalfWidth;
float cameraTop = playerCamera.transform.position.y + playerCamera.orthographicSize;
float cameraBottom = playerCamera.transform.position.y - playerCamera.orthographicSize;
foreach (GameObject parent in CullingObjectsParent)
{
if (parent == null) continue;
foreach (Transform child in parent.transform)
{
Renderer objRenderer = child.GetComponent<Renderer>();
if (objRenderer != null)
{
Bounds bounds = objRenderer.bounds; // get sprite bounding box
float objLeft = bounds.min.x;
float objRight = bounds.max.x;
float objTop = bounds.max.y;
float objBottom = bounds.min.y;
// check any part of sprite in camera view
bool isInView = (objRight >= cameraLeft && objLeft <= cameraRight &&
objTop >= cameraBottom && objBottom <= cameraTop);
child.gameObject.SetActive(isInView);
}
}
}
}
}
rolling your own culling system would rarely be more performant than Unity's
any reason why? I'm guessing for instanced stuff?
if it is, you may want to offload them to a dedicated thread (non-mainthread). Even for simple AABB intersection test it can easily kill your game's perf
cause i have to implement my own
for context this throw in gameobject parents, the script calc the camera bounds, loop through each child in given parents, get it's sprite renderer, calc sprite bounds, check 2 bounds collide then set child active or not
if anyone know any good public script for this purpose i would be a verry ahppy boy
Have you tried just checking for Renderer.isVisible? It's true if the Renderer needs to be rendered because it's in camera view or casts shadows.
I also wouldn't trust checking bounds for re-activating the object. I'm not sure if the bounds get recalculated if the object is inactive, when it's Transform changes (for example, it gets scaled).
i'm having issues adding a git url to the package manager. online people say to add the git.exe path to System Environment Variables. but my latest setup of Git doesnt even have a git.exe. it has the following.
those are shortcuts... r click and go to location of the shortcut...
the normal git for windows installer should have added git to your PATH already though, restart your pc if you just installed git
i managed to get it working! the image i sent isnt actually the git.exe that the SEV Path was looking for. it was here:
C:\Users\jacgu\AppData\Local\GitHubDesktop\app-3.4.16\resources\app\git\cmd
one day i'll wrap my head around git
er i would not add the embedded git from github desktop.
Install git correctly: https://git-scm.com/downloads/win
github desktop is a GUI program FOR git
okay will do but i actually used that setup
then add the correct git installation to your PATH
so where is the git your are reffering to
mine is C:\Program Files\Git
will give it a shot
just the folder that contains it
thanks for your prompt assistance rob
np 👍
{
// Get the correct angle (this is confirmed correct!)
float angleLabel = -(i * sectorAngle) - (actualSegmentAngle / 2f) - halfGap + globalRotationOffset;
float radians = Mathf.Deg2Rad * angleLabel;
GameObject spawnedImagePart = Instantiate(imagePrefab, radialPartCanvas);
RectTransform childRectTransform = spawnedImagePart.GetComponent<RectTransform>();
// Ensure pivot is correct
childRectTransform.pivot = new Vector2(0.5f, 0.5f);
// Calculate the exact position based on the correct angle
Vector2 offset = new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)) * radialMenuObject.centerDistance;
childRectTransform.anchoredPosition = offset;
// Make sure the image remains upright
spawnedImagePart.transform.localEulerAngles = Vector3.zero;
// Apply correct scale
childRectTransform.localScale = Vector3.one * radialMenuObject.imageScale;
// Attach text and adjust position
TextMeshProUGUI childText = childRectTransform.transform.GetChild(0).GetComponent<TextMeshProUGUI>();
childText.rectTransform.anchoredPosition = new Vector3(0f, radialMenuObject.textVerticalOffset, 0f);
childText.text = radialMenuObject.entries[i].text;
childText.color = radialMenuObject.radialText;
spawnedLabelParts.Add(spawnedImagePart);
// Debug: Draw red lines
Debug.DrawRay(radialPartCanvas.position, Quaternion.Euler(0, 0, angleLabel) * Vector3.up * 2f, Color.red, 5f);
}```
I have a radial pie menu I'm workig on, and for some reason I just can't get my images put in the exact center of each slice. I have red debug lines that correctly cut through the center of the pie whatever the number of the parts, but the placed position of the imagepart seems to be "rotated" around different amounts depending on the number of entries. It must be something obvious can anyone slap me in the face with it?
here is an image of what the above outputs
are you saying you want the image to be in the "center" of the green marked segments?
the images look fine to me - it's the text that seems off. Though if the green are the "slices" the red lines also don't seem to be centered properly
anyway why do you use different logic for the red lines as for the image position?
Vector2 offset = new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)) * radialMenuObject.centerDistance;
vs:
Quaternion.Euler(0, 0, angleLabel) * Vector3.up * 2f
These autogenerated files keep popping up. Does anyone know if I can/should just add these files to git-ignore?
so the red line does cut through the blue pie chunk perfectly in the middle of the chunk (it takes into account the gaps between the segments. . There is actually a little white dot on the middle of the white texts which represents the origin of that label.
the intention with this
Vector2 offset = new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)) * radialMenuObject.centerDistance;
was to get a 2d offset position that matches the angleLabel so that the position of the of label is centered in the slice. But it just seems to change with the number of parts anyway..
(essentially trying to get the white dot on the red line)
are there any guides to integrating 3rd party scripts? I have inherited a project that has 150 scripts that all need to be tested/merged in
Hey I'm trying to create a pick up system in dots and the way I do that is I have an Entity of an item lying in the world and when I pick it up it destroys it and adds it's prefab entity to the inventory. The problem is after it destroys the entity that was lying around in the world the prefab entity isn't working because it's referenced to the destroyed entity
does anyone know how can I solve this?
Everyone who uses DOTs can be found in #dots, which is very active.
oh thanks my bad
Where did they like come from
Like if they’re c# and built for unity just paste them into ur project and reload unity
I wouldn’t gitignore the urp settings
Everything else ur probably fine but im not 100% sure
started making a game that im gonna make possible to play in both singleplayer and multiplayer, have multiplayer sorted but am now wondering. When making my game, do i need to make different assets for singleplayer and multiplayer, with only the multiplayer ones having network object and transforms, or do i make the one player a host, or just how to handle differentiating between the two
A multiplayer game that's not connected to the internet is a singleplayer game
I have not heard of any advantages to stripping out multiplayer components for the singleplayer mode, since it seems every feature needs to be supported in both modes anyway
Does anyone know how to solve this issue please ? It appears everytime I press Play, even thou I'm not using PlasticSCM so I guess it's maybe one of the assets I downloaded from the store that does that ? 🤔
restart unity, or remove version control package maybe
Thanks, it worked 👍
(Removing Version Control Package)
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Barricade : MonoBehaviour
{
public GameObject Player; //Reference to the player object
public GameObject QuestionPanel;
public GameObject barricade;
public Text pressE;
private bool playerOnBarricade;
public Text questionText;
public Button closeButton;
public InputField Q1;
//Q&A
private string question;
private string correctAnswer;
//Points
public Text pointText;
private int points;
// Start is called before the first frame update
void Start()
{
pressE.enabled = false; //Hide the text at the start
QuestionPanel.SetActive(false);
closeButton.onClick.AddListener(closeQuestion);
Q1.onEndEdit.AddListener(checkAnswer);
//Points
points = 0;
addPointsText();
}
// Update is called once per frame
void Update()
{
if (playerOnBarricade && Input.GetKeyDown(KeyCode.E))
{
showQuestion();
Debug.Log("Question Opened");
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
playerOnBarricade = true; //Player is on the key
pressE.enabled = true; //Shows the key
}
}
``` my points only go up to 10 points and stops updating after the first barricade is answered.
{
if (collision.gameObject.CompareTag("Player"))
{
playerOnBarricade = false; //Player not near the key
pressE.enabled = false; //Hide the key
}
}
void showQuestion()
{
QuestionPanel.SetActive(true);
questionText.text = question;
Q1.text = "";
Q1.ActivateInputField();
}
void closeQuestion()
{
QuestionPanel.SetActive(false);
}
void checkAnswer(string answer)
{
if (answer == correctAnswer)
{
addPoints(10);
removeBarricade();
}
else
{
Debug.Log("Wrong Answer");
}
closeQuestion();
}
void removeBarricade()
{
barricade.SetActive(false);
Debug.Log("Removing barricade: " + barricade.name);
}
public void SetQandA(string newQuestion, string newAnswer)
{
question = newQuestion;
correctAnswer = newAnswer;
}
void addPoints(int amount)
{
points += amount;
addPointsText();
}
void addPointsText()
{
pointText.text = "Points: " + points.ToString();
}
private void OnCollisionEnter2D(Collision2D collision) //If player hits Barricade it cant go thorugh and prints Wall Hit to the console
{
if (collision.gameObject.tag == "Baricade")
{
Debug.Log("Baricade Hit");
}
}
}
Im not sure why it only goes to 10 points
!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.
that also does look like a #💻┃code-beginner question. you should add more debug logs or use the debugger to see whats happening exactly. Like see the value when you're adding points or if that method is being called at all
Ok thanks
So, every barricade has its own copy of points? Do you keep calling addPoints to this one particular Barricade?
so I personally would do the one Enemy component that then reaches out to your other components for different things when necessary. But instead of designing your other components to be "enemy specific", make them reusable by other objects. for example, do you really need a specific component for enemy health, or can it just be a "Health" component? because lots of things could have health besides just the enemies
okay well it seems you're already on the right track, just do that for movement and combat related components too
sure, you can use an interface to communicate between the components, but i'm saying to create components specifically for the types of movement and combat you want so you can modularize the enemies. so one enemy could have a WalkLeftAndRight movement component and another could have a FlyStraight movement component (using goomba and bullet bill movement as examples)
for a loot system, you could most likely make 1 class for that and use the inspector to handle any differences between enemies. Unless you plan to have functional differences, stuff like amount of loot, rarity, etc, can all be handled by just plugging in data.
As for your movement question, id try to avoid having like a EnemyNameMovement or similar. You'd wanna unify the goblin movement between anything that walks in the same way, so that code could apply to other creatures
well zelda was made in an entirely different engine. modularized components is the Unity Way™️ because the engine was designed with the component pattern in mind
okay that's cool. and i'm saying that because zelda was made in a completely different engine that just because it may do something one way, does not make it the right way to do something in unity. unity was designed in such a way that you would create components for individual behaviors and mix and match relevant components to compose your objects
if you try to fight against that then you're just going to have a bad time in actually using the engine
Well something else can disable and enable movement which "removes" the dependency. But you might just be overthinking this. I say "removes" because no matter what you do, your components depend on each other at the end of the day. Moving the dependency just changes which object is gonna call GetComponent or be assigned a value in inspector.
To give an example, lets say an enemy has an ability and becomes invincible during this time. In some way, whether it be directly or calling some character method, it has to eventually call a method to be invincible
This is just how games work. You can go the full SOLID path but it just becomes a pain to work with. The first pain already being interfaces. By default you cant reference something like IHealth in inspector
Hi. I have following functionality: I have chesspieces, that are supposed to dismember upon death. The problem is that the pieces (of the pieces xd) are not gaining the material of the original piece. For example, if black pawn dies, the shards it spawns are still white. Can't i do it by code somehow?
for abilities sure, but if you're talking about EnemyMovement, EnemyHealth, EnemyVisuals then you likely could just code each as 1 class where the difference is what you assign in inspector. I see no reason why they need to be enemy specific. The example you gave for an enemy with multiple health bars could make sense to split into a separate class but thats not really unique per enemy. That's reusable for a category of enemies
your question implies you aren't doing this through code. How do you expect the pieces to gain the material of the original piece?
I have no idea how to do it, thats why im asking
if you could give me a keyword or link, i would be grateful
Just as an example, for health, whats the difference functionally between a players health and an enemies health? Both probably have a current and starting health. Both would subtract or add to their health when whatever situation happens.
The only difference could be stuff like their starting health. This doesn't require a unique class for player/enemy when you just need to change a value in inspector
None of that is fundamentally different, this all seems like "Number can go down, and notify some other scripts that my number went down"
player can't die, they only get knocked unconscious
this isn't a functional difference, this is just language. something happens when their HP hits a threshold. The tutorial part could be a bool
enemies being stunned while the player cant is also just a bool
Also even as language it's not real. My level 100 Metagross using earthquate against the wild level 12 Pikachu, that Pikachu did not faint. It's fucking dead
It's not about creating a monolith, it's about creating a hierarchy
thats just an event
Enemy and Player would both extend some DamageableEntity script or interface
Has some OnTakeDamage and OnDie methods that can be overridden
it sounds to me that you have a lot of repeated code trying to avoid this "monolithic class"
and that stuff is a separate component from the actual Health. why should the Health component know what happens when something "dies"? it should only notify other objects that it has reached that point of "death"
Yeah that's probably fine, but you can probably add more to it
Defining events to call on damage/death, for one
we could make up stuff to worry about all day, about any implementation you do. I think the thing you should actually worry about is repeated code
Literally the only if statements mentioned here was if the character should be invincible during the tutorial and if the character can be stunned.
and the stuff like what happens when the player hits 0 hp should be an event. that way you have 1 health class, and subscribers which do something based on the event. This is already separate classes
Otherwise you have multiple health classes with the exact same logic because a few of them want to call a seperate method. This is comparable to having different health classes because one of them wants to start with more hp
Then you wake up one day and suddenly decide enemies should die when they hit 0.1 hp to make a smoother experience (just making up something to stay in the health example). Suddenly you have to go edit every health class. This really isn't good
The difference being it's not repeated code anymore. It's also not a new component per object. Surely you'd have more than 1 enemy that dies in the same way like playing an animation and being destroyed
this is a strange conversaion. virtual methods exist for this reason, to override behaviours but share others
You should just take it case by case. I dont really know enough about the other variables and stuff like rocks to suggest much.
anybody know why arrow curves like that? https://paste.ofcode.org/3sVVb9JGWNRsxKH6tMYwgE
code of bow
if you ever want a good example, source 2013 is all there to look at
but csgo leaked only 🤔
and tf2 was released in 2013 recently
dw im aware i do lots of stuff in the source community (worked on tfs2 for example)
#archived-code-general message
I really dont think it's all that valuable just looking at other code.
I see no harm if you want another perspective on how to potentially design something, not forcing you
can someone take a look
I mean yea you could look at every perspective of games that wasnt made in unity. It's not "harmful", it cant be since its learning. But the structure of what you make in unity is going to be different
sbox which is based on source 2 has moved its design to be very unity like
they did? huh sounds strange
Studying other projects can really just lead you down strange paths. And it seems you're already aware of how other games are structured.
Imo the best advice for you is literally
with the suggestions above
You dont need to make the best structure, or follow SOLID all the way down. You need a game that runs at the end of the day. Every weird decision you see in a game is because the game needed to run and that's how they chose to do it
Is there any way to get JsonUtility to make a Json array without a name? I'm trying to generate data to send on a POST request but it always slaps the variable name in front of the string if I try it. I'd rather not just built the array by hand.
tried newtonsoft json?
Seems a bit heavy to add an entire extra dependency for something that JsonUtility really ought to be able to just do
well the json utility uses the unity serialisation system which probably isnt going to do all you need it to
and unity has a package maintained already for it
its valid
the ol' "ill improve it later" but later never happens
Where I work rn we have a shared libs package, i've added some useful things to it over past years
always wise i think to build a good base of useful stuff
Beware of using too much interface. Healing/Attacking could make sense but GetHealth and GetMaxHealth might become an issue if you have a considerable amount of "Statistic".
Also, instead of using "setOnFire", "canAlertNearby", etc. you might want to use something else. Otherwise, if you have a lot of "Really Specific" behaviour, you will have a really, really long and non cohesive damage info class.
Obviously, it all depends on the depth you are looking for. If you do not believe you will scale more then that, it is way better to keep it simple as you do.
and you 😎
It is not uncommon to have a lot of "Statistic" in a more RPG still games. You might find yourself with more generic statistic such as health, armor, mana, etc. and more specific statistic such as Ability Damage, Trap Damage, Empowered Damage, Poison Resistance, Working Speed, etc. and it quickly become out of hand if every type of statistic is hiding behind an interface. The best way is to use composition instead.
By example, instead of accessing the health of a given object by doing:
object anObject = ...;
if(anObject is IHealth)
...
You would do:
Entity anEntity = ...;
if(anEntity.TryGet(...))
The advantage is that it scale really well an you can even easily define statistic purely as data if you have a system that read/use any statistic.
Yes, in the sense of statistic this amount of flexibilty is justified.
Usually, it makes thing harder to work with given that you loose the "Type" of each class.
No worries, as I said, it is better to keep what you have if you do not expect any explosion of statistic.
- If you keep what you have, at some point you might find yourself with a lot of parameters.
setOnFireseem to be a really specific an arbitrary effect for a given attack. I expect that you might have a lot of such effect in the futur. - If you keep what you have, you will most likely get into situation where you need multiple parameter for a given effect.
By example,setOnFiremight require the duration, the damage, the intensitity, etc...
But, again, if it is not the case and there is really a limited amount of effect an attack can take do not bother doing anything elaborate.
Composition again.
public struct DamageInfo
{
public DamageInfo(List<Effect> effects ...);
}
Obviously, it come with a cost if you do not cache and do not use a data-oriented approach.
Not really, it is polymorphism in this case.
public class SetOnFire : Effect {
public override void Apply(...);
}
So is it possible to have a function not apart of my job system burst to run at the same time the burst does? My issue is the function that is supposed to work during the time the burst is on in the main thread never is synchronous to the burst.
Is there ways around this?
Okay
You can add a CanBeApply or a simply returning if you detect the effect should not be applied.
If you combine both solution I said earlier, you could easily see something like:
public class SetOnFire : Effect {
public override void Apply(Entity entity) {
if(entity.TryGet("FireImmunity", out bool fireImmune) && immuneToFire)
...
}
}
It could be the first one or the second, but ideally you would use composition instead or at least an interface.
class SetOnFire...
bool CanApply(obj)
if (obj is ICanBeSetOnFire)
return false;
return true;
I know where you are coming from, having most of the data be non typed can quickly become out of hand.
Oh, if you mean having something like a string to access the statistic ? Obviously this is bad, but it is the easiest to write. You usually, you might want to associate meta data to each statistic (icon, name, description, etc) hence they all have a ScriptableObject associated. Whenever I want to access the statistic, I use the ScriptableObject.
It has the down side that some of the statistic might not have any need of a visual representation but I live with it.
Yes.
Something like:
public class StatisticDefinition : ScritableObject
{
[SerializeField] string title;
[SerializeField] string description;
[SerializeField] Sprite icon;
}
And, if you need more meta data you can even inherit from it.
No, the StatisticDefinition is mostly data. Also, GetValue would not be a function of it.
public class SetOnFire : Effect {
public override void Apply(Entity entity) {
if(entity.TryGet(Statistic.FireImmunity, out bool fireImmune) && immuneToFire)
...
}
}
public class Statistic
{
public StatisticDefinition FireImmunity => //Load and cached the ScriptableObject
}
To get the value, you still rely on the entity.
i have spent 8 hours trying to make system.speech work, is it possible even? i hope theres some easy solution i just havent found
works but only on windows
im on windows, still doesnt just work
oh, then most likely unity creating some barrier
Hi, I am working on a kind of motorcycle controller... I am using rigidbody. No w I apply some forces at the center of mass while accelerating, this gives a realistic torque. Like tilting a bit backward when accelerating and tilting forward when braking. This tilting is visible on the bikes X axis. Now the problem is this cause a lot problems on the y and z axix(falls of, flips off etc)... Now when I freeze the Y and Z rotation, the x rotation doesn't happen naturally anymore. So what should I do to let the rigidbody control the X axis rotation as it gives realistic vibe but stop it from rotating y and z insanely?
Apply a counter torque or force to stabilize it.
how do i calculate how much to apply? Can you elaborate a bit please?
I do not know how advanced / beginner this is, but I am a little lost.
I got this code: https://pastebin.com/fWCyXsRg
It's my CameraController, everything functions perfectly. The only issue I got is.. the cameraAdjustSpeed should handle how fast the camera adjusts. But even if I lower this, the camera snaps right back into place the moment I move, while it should gradually move back into place based on cameraAdjustSpeed set.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I do not see any logs, so you should start there, add some and see, if your if statements are entered or avoided correctly
Hi, I'm using an RCC controller with Fusion, but I'm experiencing issues with network transform and replication. Additionally, I'm having trouble with the network controller, where both cars move when I press the buttons. Can anyone help me resolve these issues?
Hi! Please help me with the code, I am a novice developer in unity. You need to make a counter that will be replenished when a certain object is deleted.
It depends. You'll need to look at what torque or forces are getting applied to it naturally an apply forces to counteract it.
You can also implement a sort of PID controller, that would constantly apply forces such that the object is returned to a balanced position/rotation.
When you delete the object, add one to the counter.
I did this, but it gives me an error, maybe I don't understand something because I literally started learning unity 3 days ago
"gives me an error" is much too vague for anyone to help you with
If you want help you need to share your code and your errors, and give a better explanation of what you're trying to do in the game
derp wrong message
If this is some homework, is there extra info to help you?
!learn should be you rplace for the first days
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
In my code, I need +1 point to be added to the counter when a word is deleted. ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public static int scoreAmount;
Text scoreText;
void start()
{
scoreText = GetComponent<Text>();
scoreAmount = 0;
}
void Update()
{
if (GetComponent<Word>() == null)
{
Score++;
}
}
}```
startis not capitalized correctly and will not run.- You're using at least one variable that doens't exist (Score)
- This logic is really confusing and most likely makes no sense
every single frame that this does not have a Word component attached it will increase the score by 1 (assuming you fix the issues Praetor pointed out)
What does it mean for a "word" to be deleted?
what's a word?
How are words being added/deleted/edited?
If you want to become Unity Developer, I would suggest following available tutorials step by step. If it's just a homework and you don't plan to master it, I would suggest the following approach instead:
- Open up ChatGPT.
- Describe your situation.
- Copy the exact error from the console and paste it into chat.
- Read what it responded and apply appropriate changes.
- If problem is not resolved, return to step 2. If you get stuck (ChatGPT can't come up with better solutions or starts writing stupid things), seek help somewhere else.
ChatGPT often writes stupid things, but it's more likely to write something useful if your problem is basic. Since you're beginner, your problems will be mostly basic. Remember: the more detailed your description is, the more likely you will be to get the correct answer. Otherwise, you'll only cause confusion.
i would not recommend any of those steps
Thats how you limit your thinking to what ChatGPT provides no matter if you understand the terms of it or not
plz dont make more "vibe coders"
following available tutorials step by step
just this part is plenty enough
they're quite brief
if you don't want to fully master unity, just don't go through the advanced tutorials
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this is plenty
Good enough for people who just want to pass the subject they're not interested in and focus on things they're actually interested. 30% of subjects I was forced to study were useless in GameDev industry, so I understand someone's pain. If he really was interested in becoming Unity Developer, he wouldn't have a "do it for me" approach.
ah yes, because problem-solving in general is not a useful skill at all
to be blunt; the majority of your message, and the part that's listed as steps, is about chatgpt. we really don't need someone coming in and seeing just that part and thinking it's a good idea for learning.
It is useful. But we can always learn problem-solving related to the topic we're interested in instead.
If he really was interested in becoming Unity Developer, he wouldn't have a "do it for me" approach
you are severely underestimating the amount of entitlement and laziness that many beginner devs have, especially when they come here for help
problem solving is not topic-specific
problem-solving in an unfamiliar topic is a great way to actually practice problem-solving, actually.
especially when there's plentiful resources to help, which is definitely the case here
It might be the case. I was like this when I was 12.
The odds that problem-solving skills related to culture, electric current, gym exercises or radio waves will help me as Unity Developer are small, but never 0. 💪 The statistics and web development helped me a tad though.
You got your point, no common ground between individuals here, lets let go
can someone take alook
Apparently you are making the arrow a child of the string
And the string has a weird scale
Parent rotation possibly
And some rotation weirdness going on too yeah
but it has to follow the midpoint of string so I child it to him
Find another way. Don't have a non uniformly scaled parent
You can simply spawn it at tthat position instead of make a child
It needs to follow the string when it's drawn though
or use a position constraint component
Constraint or manually moving it are your main options
Okay I will try constraints thanks. 
Hi, I need a save system that will store the state of objects in the scene, including which objects were added, which were deleted, etc. Is there any recommended package for this, or what's the best way to create such a system?
why does the invoke in GenerateNewMap show an error? the RoomGenerator is subscribed too it, so its odd for it to show an error
public class MetroMap : MonoBehaviour {
public static event Action MapGenerated;
void Awake() {
GenerateNewMap();
}
void GenerateNewMap() {
MapGenerated.Invoke(); // NullReferenceException: Object reference not set to an instance of an object
}
}
public class RoomGenerator : MonoBehaviour {
[SerializeField] MetroMap _metro;
void Awake() {
MetroMap.MapGenerated += GenerateRoom;
}
void GenerateRoom()
{
}
}```
you invoke the event before anything is subscribed to it
ah
also you typically want to null check your events when you go to invoke them, you can use the ? operator to do so like MapGenerated?.Invoke();
I'm trying to recreate what the SOAP asset does by Scriptable Variables that can be of different kinds, even lists. Note: I am not familiar with the specific implementation as I don't have the money to buy it (otherwise the problem would be solved) so I'm trying to recreate it on my own.
Following git-amend's tutorial I manager to get this script:
public class ScriptableVariable<T> : RuntimeScriptableObject
{
[SerializeField] T _initialValue;
[SerializeField] T _value;
public UnityAction<T> OnValueChanged = delegate { };
public T Value
{
get => _value;
set
{
if (this._value.Equals(value)) return;
this._value = value;
OnValueChanged.Invoke(value);
}
}
protected override void OnReset()
{
OnValueChanged.Invoke(_value = _initialValue);
}
}
That can be easily extended via inheritance and allows me to create a generic list:
public class ListVariable<T> : ScriptableVariable<List<T>> { }
Now my question is how can I make the list generic? Because of course I cannot create a scriptable that has a list of value T, I'd need to either ask the user to specify the type on creation or create different specific lists, which is not very flexible I gotta say...
#region Specific Implementations
[CreateAssetMenu(fileName = "Game Objects List Variable", menuName = "SOAP/Variables/Game Objects List")]
public class GameObjectListVariable : ListVariable<GameObject> { }
[CreateAssetMenu(fileName = "Integer List Variable", menuName = "SOAP/Variables/Integer List")]
public class IntegerListVariable : ListVariable<int> { }
[CreateAssetMenu(fileName = "Float List Variable", menuName = "SOAP/Variables/Float List")]
public class FloatListVariable : ListVariable<float> { }
[CreateAssetMenu(fileName = "Bool List Variable", menuName = "SOAP/Variables/Integer List")]
public class BoolListVariable : ListVariable<bool> { }
#endregion
Am I missing anything?
I'll add that, though I want to ensure the order means it wont ever need the nullable type
it's not a "nullable type", because Action is always nullable being a reference type, this is the null conditional operator.
but anyway, you just need to invoke the event later than you currently are, such as in Start instead of Awake
what I'm struggling with is getting the order of things correct. I keep using Awake/Start interchangeably which isnt ideal. I keep trying to work where some Awakes need to happen before other Awakes, and then some Starts have to happen before other Starts
the Map has to complete its generation, before the Room can be generated, then that has to happen before I allow anything to spawn
use Awake to initialize an object's own state (or subscribe to static events) and use Start to reach out to or affect other objects.
https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
You can make a non-generic, abstract base class for ListVariable and then have a
[SerializeReference, SerializeField] List<ListVariableBase> ...```
You do need something custom for serializereference drawing in the inspector though. There are assets/repos for that
SerializeReference being the key here
Allows polymorhpism
what would you suggest I do to ensure everything gets executed in the exact order I need? Events feel like the right approach, but I've felt sure of things in the past then later found that approach sucks
Initialize components yourself as much as possible
I do this for basically everything
@whole sorrel You can use this for inspector drawing: https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown
So I need to create a Wrapper that doesn't have any generic and inside that wrapper have a ReferenceDropdown that changes the type of list, right?
so subscribe in Awake, invoke in Start?
Not so much a wrapper but it just needs to inherit from the non generic base class
But I think you kinda get the idea
SRef is really powerful
Thank you, I didn't know that library
The dropdown changes the type per-element, not for the whole list
for this, yes. that would be the way to do it, because without messing with script execution order (which ideally you wouldn't need to do), you cannot guarantee that one object's Awake is called before another's
Oh shit
This is OP
SerializeField is not needed when using SerializeReference, fortunately
Ah yeah waasn't sure, thanks for clearing it up
me who made my own system ages go when this exists 😐
Me who made my own drawer even though I know this exists 🧑💻
(I really just wanted to learn)
its a habit im trying to get into more
even if two components share the same object, I'm avoiding a bunch of GetComponent calls like I usually do
Most of what i create will get initialized by something else that loaded the scene anyway but it gives greater flexibility (and means i can also await initializations if async!)
e.g. load level, await init + load, hide loading screen
Hey everyone, I am trying to add a package dependency tarball file to my custom package. What is the correct path to fill in the package.json? Like would it be "file:../Library/PackageCache/com.mypackage/Packages or something? Not sure it belongs to coding, but it at least is a json file. Point me to another channel, if it fits better.
If I would import it throuigh packagename thats available in unitys registry, yes. But its a custom package for visionos from unity, which only is distributed as tarball, the heck why 😄
Im currently working on a 2D roguelike, and made a prototype for handling active-use items - but before I move on, I wanna check if there's a more efficient way to go about this
I basically made an Item class, and from there I made a TNTItem script so I could make a scriptable object and use that? But it seems off because this would gradually be cluttered
if you put the tar.gz in Packages/ it will probably be added automatically
a normal folder in there thats a package will be.
So its a Package folder inside my package to deliver the file to other projects. I import my through github for example and inside the packagefolder of my package, there is a subfolder called Packages
err what
whats going to be tricky is getting the process to begin again once I need to load the next room. I've done it a few different ways but each time it feels like it introduces problems when I need to get the next room after one has already been created
OH GOD IM STUPID I JUST REALISED
if you refer to my text, no, it was just very badly explained 😄
What's the issue about it exactly? Use a stack or queue maybe
Now i understand, i think you would just have the package id dep but ofc how is the package manager meant to auto get this dep? it cant so i guess it just wont?
So are you only generating the rooms next to the one you are currently in?
@hexed pecan maybe I'm reading this incorrectly but with SerializeReferenceDropdown, don't I still need to give the list a type?
git packages cannot have other git packages a deps so im gonna say unless the user installs the tar dep manually before it will just shit the bed @plucky inlet
That still doesn't fix the issue of the scriptable not being instantiable
well its because to do it the first time, I need to do the initialization and then as I write the code I progress through it. But the first time I tried to do it, I basically created an entirely different loop that allowed me to cycle through the maps
But mine is having a git package as base and a tarball file inside the git package which should be referenced. Its not another git, so that should make a difference, probably 😄
Wdym? It would be a List<ListVariableBase> or something
maybe its possible to auto install the tar as a package when your package is first installed?
But "install" basically means, it is just adding the file as a dependency, isnt it? So you mean, using some unity api for packagemanager to load additional packages?
there is an api to check some package stuff: https://docs.unity3d.com/ScriptReference/PackageManager.PackageInfo.html
you can maybe check if a dep is installed, and if not copy the .tar.gz into Packages/ ?
tbh im not sure what unity does when you install a tar package via the gui
It's one way, but as you already noticed it's not really efficient since you only create 1 instance for each SO.
A better way is to have an SO for a generic item and the effects (or whatever makes the TNT different) be a field which can either be another SO or a plain C# class.
You would need to have a way to serialize those, like this package does: https://github.com/mackysoft/Unity-SerializeReferenceExtensions
Here is what a SO looks like for me:
It just created a reference to that file
I see, ill try it out. Thanks
Mhh thank you I'll think it over
"com.unity.services.vivox-visionos": {
"version": "file:./Assets/MyPackage/Packages/com.unity.visionos.vivox.unityVisionOsSdk-16.5.4.tgz",
"depth": 0,
"source": "local-tarball",
"dependencies": {
"com.unity.services.vivox": "16.5.4"
}
},
Thats all its doing
isnt that good, its installed now?
no, thats when I import it right away through packagemanager. Thats not when I import it as a dependency of my package
In that case, it would be in the dependency array of
"com.unity.services.vivox-visionos": "file:./Packages/com.unity.visionos.vivox.unityVisionOsSdk-16.5.4.tgz",
But that gives me: Version 'file:./Packages/com.unity.visionos.vivox.unityVisionOsSdk-16.5.4.tgz' is invalid. Expected a 'SemVer' compatible value.
and semantic versioning is not working in that case, so im out of ideas 😄
yea the value should be the version not some path to a file?
the dependencies are only package id and a version
Yeh, thats why I wonder, where the heck do I put it if possible at all
can you not install it similar to how UPM lets you? https://openupm.com/packages/com.boristhebrave.sylves/#modal-manualinstallation
If you correct you dependency to be a version and try to install your package without visionos installed, what happens?
you mean, vivox without the visionos suffix?
yea, does it deny the package install as it cannot resolve the package dep?
I am actually testing it right now to just throw it with the number
where I work we have our own packages hosted on jetbrains spaces for our internal packages
expected: com.unity.services.vivox-visionos (dependency): Package [com.unity.services.vivox-visionos@16.5.4] cannot be found
yeh, hosting on a custom server would be the other option, for sure
you can see if this is on open upm too but otherwise you can just inform users to install vision os first
well, so somehow i gotta force the user to add the tarball file for now, from wherever, because unity does not provide any other form yet
in the gui its doable and the error hopefully is good enough to remind them that this must be done first
Yeh, not very convenient tho and I wish, there was another way. But maybe, they include the visionos part in the global registry some day or at least make an actual package in their registry out of it. Thanks tho for your time and suggestions! 🙂
np, ive fucked with packages a bit but shame it cant do this. At least we have the package manager at all 🦾
If I have a gameobject with a script attatched to it, with the script containing a bunch of float[], int[], etc.(used for saving data local to that gameobject basically)
but now I want to replace those float[] and int[]'s with a structure as:
struct[] NewData;
where NewData instead contains those float and int arrays
is there an easy way to tell unity to transfer that data from the old arrays to the new array of structs?
You can use ISerializationCallbackReceiver to get a callback after your script is deserialized, check if it has data stored in the old way and convert it to the new way.
It means you have to keep the old fields around, but you can make them private and mark them as obsolete to ensure they never get used.
oooo awesome
tysm!!
This approach is ideal if you are making a plugin used by others. But if it's just your project, you can always go in and edit the scene or prefab files directly.
yeah this is for the former, tysm!
do I want this to be its own script, or do I want to tack on the ISerializationCallbackReceiver to the main script itself?
trying to understand how this works and how I should use it
On the script itself.
thanks!
Do I probably wanna do it in OnBeforeSerialize or OnAfterDeserialize?
ah probably onbefore
OnAfterDeserialize, for converting the old data after Unity has deserialized it.
before
ok
it runs before awake even
oh wow
` private void Update()
{
Vector3 worldPosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);
transform.position = worldPosition;
}
`
This script is supposed to make the Cursor go to the mouse Position. This Works, however the Cursor goes to the same X axis as the Camera, which results in the cursor not getting rendered. What can i do? im using cinemachine
how do i fix the error: RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same, when running Unity ML Agents? oh, and unity editor also likes to freeze after a bit it runs same for the built game
Here's an example of how to use it.
public class SerializationCallbackScript : MonoBehaviour, ISerializationCallbackReceiver
{
[SerializeField, Obsolete]
private float[] floats;
[SerializeField, Obsolete]
private int[] ints;
public MyStruct[] NewData;
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
// This can be empty, or you can make sure the old fields are definitely empty.
floats = null;
ints = null;
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
if (floats.Length > 0 || ints.Length > 0)
{
// Convert to struct.
}
// Clear the old fields to avoid duplicate data.
floats = null;
ints = null;
}
oh thx
I made the interface implementations explicit, so you're not adding new public methods to a script others might be using.
tysm!
if float[] and int[] were previously public is it fine to make them private now?
Well, that's up to you to decide. It would be a breaking API change if others might have been accessing it. If you're following SemVer, that would be a major update.
yeah
But it's fine to make them private and add [SerializeField] for this
For personal projects where you don't need to worry about backwards compatibility or such, can you get rid of the old fields after you have reserialized once?
just FYI, you do not need to use SerializeField for public variables
You can even go as far as renaming them and use [FormerlySerializedAs] to make it more clear they are not to be used.
[SerializeField]
[FormerlySerializedAs("floats")]
private float[] floats_OBSOLETE;
ah got it
does anybody here know how to make my character controller jump continuesly while HOLDING spacebar, using the new input system?
I already have the code for jumping and I have a jumping cooldown
But [Obsolete] also works well, IDEs will always list them last and crossed out.
i think you are not mentallystable
I just want my character to continuesly jump while HOLDING the button
They confirmed this is for a library/asset.
Yeah, I'm just wondering
heck
Oh, yeah. That's a good thing to do. Rhys made a plugin to help with reserializing all assets to the new format.
https://github.com/rhys-vdw/dirty-boy
Unity editor utility to manage dirty status of assets - rhys-vdw/dirty-boy
I was about to say, ISerializationCallbackReceiver can be called in a background loading thread, so you can't access most Unity APIs.
I guess you guys need a reference to my existing code, right?
Start by looking up how to detect if a button is being held with the new input system
With CC, you would apply the jumping velocity every frame in Update when the jump key is being held
If this is necessary, you'll have to just do this conversion in Awake. There's also the undocumented __internalAwake() that is called before the normal Awake, if you need to ensure this happens before any user code.
ooo ok
Ah yes, the internal awakening
I didn't realize you need to do this
Or maybe im not understanding it
shouldn't it be FixedUpdate? Also in my script I have defined the jump method outside Update. Do I also have to change that?
I think prefabs might automatically reserialize, but not scriptable objects.
Nah CC is designed to be used in Update
Most other physics related stuff goes into FixedUpdate though
so I don't need to modify my existing jump method?
Does not matter where it's defined really. You can still call it from Update
oh
that feels like it's the noobest question ever, sorry
I'm really new to game dev
It depends. You can show your !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.
I guess I'll do that and implement it in my existing jump method
and call it in Update
if it's not there already
can someone program me a mobile button that if you click it a sound plays please @somber nacelle no i didnt learnd for that or something i tryed to do it myself but i dont understand it
we're not here to make stuff for you, we're here to help you make stuff yourself
break that down in to separate portions
how to make a button, how to play audio
This is like the second time you've asked
People have given you direct steps and resources for learning