#archived-code-general
1 messages · Page 125 of 1
This is the one that made it click for me
https://toqoz.fyi/thousands-of-meshes.html
GPU instancing is a graphics technique available in Unity to draw lots of the same mesh and material quickly. In the right circumstances, GPU instancing can allow you to feasibly draw even millions of meshes. Unity tries to make this work automatically for you if it can. If all your meshes use the same material, ‘GPU Instancing’ is ticked, your ...
it also involves some neat rendering stuff but there's a compute shader that does all the moving of the objects
oh very cool, I'll check it out, thank you
I have a question about subscenes. I'm really early in my project, an rts, and I decided to make the switch to DOTS before getting too far along and having to deal with it later. When reading the ECS workflow on Unity docs, it talks a bit about sub scenes, it seems like this is great for streaming scenes for performance vs loading a giant scene. So, my question is, if i'm just working in a test scene right now, and not building anything out with the environment or anything like that yet, I'm assuming I don't need to worry about sub scenes yet then?
Not sure if anyone would like to take a try at my problem but any help is much appreciated. I have a script rotates the camera holder, head, to simulate recoil. When I attempt to shoot while the camera is rotated, the bullet hits where you were first aiming, even if the head was rotated up. I dont know if it is an issue with my projectile calculations (5th image attacked), but I find that unlikely as it is able to hit where you are initally aiming. If any more information is needed I would be more then happy to attach it
Someone might like to take a try if you posted your code correctly
So do you plan on helping or being bitchy?
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
The least you can do is to post code in a way that is easy for other people to read.
now, not a chance
Hey, I'm trying to call DestroyObj(); from multiple children objects from another script on this script. If I do GetComponentInChildren<> it works but only to one of the objects. I tried doing GetComponentsInChildren<> but I got an error. Any help?
what is DestroyObj
yes, because getcomponents returns an array
Its on another script.
the [] thing?
yes, that is the syntax for an array literal
you can't just stop at "I got an error"
GetComponents returns an array
that's not useful
you got an error because you tried to call DestroyObj on a RecipeItem[]: an array of recipe items
the [] syntax is used to get a specific item from an array
you can iterate over an array with foreach
foreach (var num in numberList) {
Debug.Log(num + 1);
}
I have a projectile whose rigidbody's collision detection is set to "continuous dynamic" moving through a trigger at high speeds. The trigger does not seem to react consistently. Any tips?
wait I think I figured it out now
give me a minute
Awesome! it worked!
Thanks guys
@worthy willow as a general tip, if something is acting differently than you would expect, the best first step is to read the documentation. Doing that would have told you that it returned an array, not an individual item
(and to look at the error message)
that too
Will do. thanks for the advice
but it helps to read the documentation to better understand what the error message may be telling you
Apparently continous collision just doesnt work with Triggers. Why?
what are u using continous on? Triggers are not a physical interaction
high speed projectile
try Continuous Speculative then if u dont need very very precise collisions
which bullets are too fast to see anyways
According to unity forums triggers just dont care about continous anything. Which I guess makes sense? If you hit something physical you're stopped, continous collision makes sense there, but if you're moving fast enough, you can obviously just... jump over the trigger completely in a single physics frame.
Then what do you do? Fire OnTriggerEnter and Exit at the same time? Does Stay go off?
It's definitely weird.
@dawn nebulaRaycast between your projectile updates for hit detection.
Not only is this much more performant than running actual physics bodies, but it's going to be much more accurate.
ya it just changes who is doing the thing
as opposed to some arbirary trigger finding a thing and doing something, it's the projectile who does the search
and that's kinda annoying
Everyone does projectiles this way. It's pretty much the standard.
You just can't rely on physics engines to perform hit detection on tiny bullets moving at 500 meters per second
It's never going to happen
so should i do a raycast, getcomponent for some component I created and then call some method there?
I've seen stuff where you'd also raycast behind if it's traveling too fast
rigidbody stuff does work though for high speed projectiles
You should have a class for your bullets. These classes can have behaviors such as CheckHitDetection()
where you bake the raycast behavior into it, and it returns a valid hit or not
If you remove rigidbodies from your projectiles completely, and move them manually using Transforms, you can get really nice performance
I know that Unity has methods to raycast an entire collider shape as opposed to just a ray
It depends on your projectile. Generally raycast is fine for little bullets
for a rocket, a shape cast would probably be better
Hmm. Question then.
Right now I have a "gravity zone" that's a script with ontriggerenter/exit. Pretty massive collider usually so unless something is moving at ludicrous speeds I doubt it would miss it.
The point of this object is to tweak the velocity of any rigidbodies in its trigger by some value ever frame.
If it's the projectile itself that's handling the enter/exist of triggers, how do I cleanly replicate this behaviour?
Yeah you'll probably want rigidbody projectiles for this then.
Whenever something enters the trigger, just check if it's a bullet. If it is a bullet, just disable the gravity for that bullet or whatever you're doing.
I mean I'm doing that already. It's just I want these bullets to both interactwith potentially giant gravity zone triggers and also have sorta small hurtboxes to do damage to things it hits.
Guess I can just do both?
normal triggers for the gravity zones and raycasts for the hits
If the gravity zone hitbox is really large, you don't really need to worry about it missing
the hit detection I'm talking about is for hitting thin walls, players, NPCs, etc
it's like a couple dozen unity units
so like
you'll probably be fine
probably fine
@void basalt For the calclation then should you project FORWARD into the next frame or check what you passed through last frame. i assume the former?
If determinism is important then you might have to use... mathematics
You could make it multiple step, calculate with normal gravity until your bullet reach the trigger, and proceed rest with affected gravity
Just the last and current simulation
is all you need to check
so yeah, you should check after they've moved
ok but the hitbox would extend massively from your old position to the new one
This tells you when the physics engine fires
wym?
We aren't extending the hitbox of anything. We're just raycasting from lastPosition to currentPosition
It's just shooting a line between them, to figure out what it hit
ya so if the projectile is somehow teleported between when you save the last position but before you do the raycast check from your current position, they raycast will extend from your current position to your pre-teleported location
Don't think of this as a multi-threaded scenario. This usually won't happen
code gets executed from top to bottom, one line at a time, one file at a time
you should always be able to tell when your code gets executed
Code start -> Bullet move -> Player Move -> Bullet hit check
should generally be the order in which your code runs
as an example.
If your bullet moves, then teleports somewhere else, that new teleport position should be the current position.
you'll still have the same last position from the last simulation update
reading
So when it teleports, you don't want it to check against the last position?
If so, just overwrite the last position when that happens.
blegh
then you'll have your lastPosition and currentPosition the same, and the hit detection basically will never return true after a teleport.
why not check forward btw?
i guess the difference would be, in the case where you destroy on the trigger overlap
for one frame the projectile would be in the trigger
but looking ahead you wouldn't ever see it in the trigger
assuming Update had a chance to fire
man
physics sims bruh
You also only need to perform the raycast inside FixedUpdate
it would be wasteful to do it every Update() frame
(assuming you're still using rigidbodies)
ye I figured
separate question
let's say I have 2 vectors
I want to rotate some third vector by the angle between those 2 vectors
how do
@dawn nebulahttps://docs.unity3d.com/ScriptReference/Vector3.Cross.html
like this?
There's probably a better way of doing what you want
The angle between them on which axis and rotate the third on which axis?
You're missing information in your question
Vector3.SignedAngle
To get the angle
And make a quaternion with AngleAxis to rotate the vector by that angle
Need an angle axis for signed angle
I guess that makes sense?
would that be the cross product of those 2 vectors?
@leaden ice
in your pciture it's whatever axis is coming out of the paper/screen
you mean the red?
no the black
are u trying to rotate the black or red vector?
red vector
psuedocode:
float angle = Vector3.SignedAngle(solidRed, dashedRed, axis);
Quaternion rotation = Quaternion.AngleAxis(angle, axis);
Vector3 result = rotation * originalBlackVector;```
your image implies you want to rotate the black one
by the difference in angle between the two black vectors
i thought it was the other way around from the drawing too
so that's what I wrote code to do
aw shit mb then
yeah the drawing is the opposite - so my code above is going by the drawing
I thought the doted vector and the "I need this" was enough to show I wanted the theoretical red
I thought it was saying "i need this angle"
and then rotating the black by that 😆
either way
just do it the other way around
alright clearly my paint skills are not up to par
same deal
Pretty sure you can get the angle difference by doing
var diff = Quaternion.Inverse(fromRotation.rotation) * toRotation;
From and To may be reversed
Thanks works.
oh yeah Quaternion.FromToRotation also works
Hello! How do I make the variable "numberofJumps" add one when it's the ground instead of it waiting to add one after it gets off the ground? Here's my code: https://pastebin.com/Y9wUEkB1
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.
Before you make fun of me, i will clean up the script im just trying to get things working
@urban stream Hot tip: clean up first before asking for help. You'll get help faster.
that is pretty easy, just create a gameobject. Set the tranform ' forward and rotate it by 30 degress and now the new forward is result
i f*cked up
I used git on a unity project for the first time on something that is overdue
and now i have a merge conflict
Oh no
i truly done f*cked up
merge conflicts are easy to fix, it just depends what the conflict was actually on
hopefully your fix doesnt mean u force pushed or something..
im on a different branch thankfully
im sure theres a better solution that im unaware of (if there is please tell me i really want to know), but you can create a variable called previouslyGrounded, and at the end of the fixedupdate you can set it to previouslyGrounded = isGrounded
idk if what im saying makes sense
and to check if it has changed you just do previouslyGrounded == isGrounded
are you trying to do max jumps value?
for example, I can jump no more than 3 times before I am grounded
you then need to make numberOfJumps variable, yes
private int currentJumps; // jumps in the air (when not grounded)
private readonly int maxJumps = 3; // let it be e.g. 3
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && currentJumps < maxJumps)
Jump();
}
private void Jump()
{
currentJumps += 1; // one more jump
rigidbody.AddForce(Vector3.up, ForceMode.Impulse); // AddForce or whatsoever
}
private void OnCollisionEnter(Collision collision) // or smth similar
{
if (collision.CompareTag("Ground"))
currentJumps = 0; // when collided with ground - curentJumps is set to 0
}
@urban stream smth like this should work
Does anyone know why are Backspace and Delete keys not triggered here?
private void LookForEvent()
{
StartCoroutine(LookForEventCoroutine());
IEnumerator LookForEventCoroutine()
{
yield return _waitForEvent;
while (Event.PopEvent(_currentEvent))
{
print($"nice keyCode: {_currentEvent.type}");
}
StartCoroutine(LookForEventCoroutine());
}
}
They should though. They are part of EventType.KeyDown, aren't they?
Why are you doing this? I have no idea why you'd be consuming events yourself like this
I am trying to work with Events, cause I am trying to create my custom InputField for game.
TMP_InputField also has this thing
but it does work there
Does this work ? Meaning can I call a physics simulation in Update() ? Or shall I run it somewhere else ?
void Update()
{
...
for (int i = 0; i < simulationSteps; i++)
{
...
SimulationScene.Simulate(Time.fixedDeltaTime);
}
...
}
yeah, don't do that
you're going to create massive lag
And I guess my physic will not be simulated ?
It will be
which is why it will be so laggy
Ahaha, ok then I'll change my implementation
What are you trying to do in the first place?
I want to draw a trajectory
You can definitely do that with physics steps, and I know unity recommends it, however you will experience awful FPS drops
to the point where it just doesn't make sense
I know that I can use a math approach, thing is it is a space simulation. The game applies newton's law to the closest planet. So I figured that it is simplier to use physics steps
Definitely best to avoid the physics engine in this case for predicting trajectories. Physx performance in scenarios like this is absolutely awful specifically when it simulates multiple times in a single frame.
Especially since it's already a space game with tons of stuff going on
What is your advice then ?
You can obtain the velocity of rigidbodies
and you can estimate their path from that
Is anyone familiar with the load errors i get in this webgl project? https://vaggelischristopoulos.eu/PolarWebTest/index.html
This shouldn't require a physics engine.
If they have a store of all gravity producing objects then it's a simple loop.
However, I do believe differentiation can be used here, but I'd have to remember exactly how I'd go about that.
idk if this is the place to put this but I am currently working on a dream game that is similar to Tarkov, Rust, and DayZ but in VR and i need ideas because I suck at implementing things plus if I could get some help anyone who works with VR in Unity please DM me I would mainly ask for ideas but if I had a question or two like how shit stays and servers would work in VR again if this isnt the channel to ask please point me in the right direction
I definitely would not differentiate unless this is an EXACT calculation that needs to be performed. Approximations would be better and realistically the 0.001 inaccuracies wont matter
I don't really need the exact calculation, the thing is I have a dedicated function to calculte gravity, to which planet apply it and it based upon the distance between the different objects
since this is dynamic i figured that resimulate was the easiest thing to do
- In my input service, i want to behave differently in build vs in editor. I read about the conditional compilation, but i'm not sure whether i use this properly or not, since rider tells me that some code is unreachable. So is this correct?
// meant to be "if in editor"
#if UNITY_EDITOR
// get mouse input
return Input.GetMouseButtonDown(0);
#endif
// else return mobile device input
return Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began;
correct
since in editor the compiler will see both return statements and the return below is not reachable
but outside the editor the above return will not be compiled so the below one will be executed instead, if you want to get rid of the warning, you can use # else or #pragma warning disable (not recommended)
# if UNIXXXX
first return
# else
second return
# endif
- And one more: i want to load a scriptable object from resources, get data from it and unload it immediately. Does Resources.UnloadAsset handle this? For some reason my data gets corrupted after calling it and this is very bad
pretty dumb question... why does my game build doesn't get recognized by discord for screensharing? is there anything i should do to fix this?🤔
What're you doing with the SO?
Copying some data and not referencing it, hopefully.
- Here's how it's used. In a nutshell: load, read data, unload
var colors = Resources.Load<GameColorsConfig>(themePath);
var theme = new GameColorsRuntimeData();
theme.Load(colors);
Resources.UnloadAsset(colors);
- Behind the Load():
public void Load(GameColorsConfig data)
{
PlayerColor = data.PlayerColor;
ObstacleColor = data.ObstaclesColor;
BackgroundColor = data.BackgroundColor;
ParticlesColor = data.BackgroundParticlesColor;
}
This is the coding channel #🔎┃find-a-channel
What're those properties?
Are they references or values (structs/primitives)?
What do you mean by your "data gets corrupted". I'm assuming, not the SO but the properties you copied.
- No, SO values are changed
How are you verifying?
- Alas, for me and my collegue it's different. For him, all colors are rest to (0, 0, 0, 0), and for me they get mixed
- Just docking the SO's properties and observing them. Magically they do change
Any subsequently loaded Scenes or assets that reference the asset on disk will cause a new instance of the object to be loaded from disk.
By docking, are you referring to loading them again? They wouldn't be the same assets.
- By docking i mean selecting an asset, prossing alt+p and watching it from the editor. I.e. viewing it in unity through the inspector
What you see in the inspector wouldn't be what was loaded.
- It's not about mismatch. Let's start from scratch, because this is going in the wrong direction
- The script above loads an SO asset from resources does not modify nor stores a reference to it, and unloads it. After this, for whatever reason, data inside the mentioned SO asset is changed
Create a new scene with only a simple script that simply loads and unloads the asset. Not modifying or copying any data. Ensure it isn't something else that you could be doing.
The data should not change.
- Scriptable object has no setters on its properties. It simply cannot be modified with my scripts
- Furthermore, the above code is the only place where this asset and its class are used. Nowhere else in the game
- Here's the result of this btw. Before and after
I still believe you ought to isolate this problem by excluding anything and everything else that you've got in the scene.
Else this discussion will not go anywhere. Show that with nothing else in the scene, the data is corrupting.
- While i'm setting it up, here's a quick note: after i remove the unload asset invokation, it does not corrupt assets anymore. Any thoughts on how can this be related?
Multiple access of the same asset on disc (inspector/programmatic etc) but I doubt it.
- Same results. Here's the script that calls the above code:
public class SOCorruptionTester : MonoBehaviour
{
[SerializeField] private GameThemes _gameTheme;
[SerializeField] private bool _darkTheme = true;
private ResourcesGameThemeResolver _themeResolver;
private void Awake() =>
_themeResolver = new ResourcesGameThemeResolver();
private void OnValidate() =>
_themeResolver?.Resolve(_gameTheme, _darkTheme);
}
- And also, this time the inspector crashed with an error. See screenshot. After i exited play mode, the error is gone and values are mixed again
- Console shows no errors btw
- I believe it's a bug on the unity's side?
- Hello?
I've created a test sample and could not generate your findings: ```cs
public class Sample : MonoBehaviour
{
public Color32 color;
private void Start()
{
var data = Resources.Load<SOExample>("Data");
color = data.color;
Resources.UnloadAsset(data);
}
}
public class SOExample : ScriptableObject
{
public Color32 color;
}```But interestingly enough, if you access the the SO when resource attempts to load the data, you get an error.
Not inspecting the SO instance when the application runs, causes no issues.
The sample copies the correct color and the SO retains it's color.
- I can try to pack my project's piece and send it to you to see if this happens on your end as well
I'm not going to download or run your application.
I'll just show a tiny video of it being fine.
- Bruh. Project, not application
- Cool! Should i do the same?
Not sure. I'm only informing you that I cannot reproduce what you've shown.
- If you're worried about me hacking you or whatever lol, i can link a github repo of this project, where you can copy scripts yourself. But the folder hierarchy, scenes and SOs are up to you then
That's not my concern or my job. I'm showing you that it's not reproduced on my machine with the above code illustrated.
- Again, cool, i'm glad it's not the case for you. But for me it is, any thoughts on that?
You've got something else going on.
- And what could it be?
Reminder that viewing the SO instance while loading the resource causes the Unity Editor to crash.
- On my end (xbox game bar recorder missed popups from unity and displaced the cursor a little)
- Values appear to reset to some values, idk
Hi im trying to add Interstitial Admob ads every fourth scene change for my mobile game , however i get lots of errors , Heres the script
`using UnityEngine;
using GoogleMobileAds.Api;
public class InterstitialAdManager : MonoBehaviour
{
private InterstitialAd interstitialAd;
private int sceneChangeCount = 0;
private int interstitialFrequency = 4; // Number of scene changes before showing interstitial ad
private void Start()
{
// Initialize interstitial ad
string interstitialAdUnitId = "YOUR_INTERSTITIAL_AD_UNIT_ID";
interstitialAd = new InterstitialAd(interstitialAdUnitId)
{
AdUnitId = interstitialAdUnitId
};
// Create an ad request
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial ad
interstitialAd.LoadAd(request);
// Subscribe to the OnAdClosed event
interstitialAd.OnAdClosed += (sender, args) => HandleOnAdClosed();
}
// Method called on scene change
public void OnSceneChange()
{
sceneChangeCount++;
// Check the scene change count
if (sceneChangeCount >= interstitialFrequency)
{
// Check if the interstitial ad is ready to be shown
if (interstitialAd != null && interstitialAd.IsLoaded())
{
// Show the interstitial ad
interstitialAd.Show();
// Reset the scene change count
sceneChangeCount = 0;
}
}
}
// Event handler for the interstitial ad closed event
private void HandleOnAdClosed()
{
// Load a new interstitial ad when the previous one is closed
AdRequest request = new AdRequest.Builder().Build();
interstitialAd.LoadAd(request);
}
}
`
Any help would be appreciated
(I think im using outdated things in my script)
You'll have to show the error messages too
I will
'InterstitialAd' does not contain a constructor that takes 1 arguments
'InterstitialAd' does not contain a definition for 'AdUnitId'
'InterstitialAd' does not contain a definition for 'LoadAd' and no accessible extension method 'LoadAd' accepting a first argument of type 'InterstitialAd' could be found (are you missing a using directive or an assembly reference?)
'InterstitialAd' does not contain a definition for 'OnAdClosed' and no accessible extension method 'OnAdClosed' accepting a first argument of type 'InterstitialAd' could be found (are you missing a using directive or an assembly reference?)
'InterstitialAd' does not contain a definition for 'IsLoaded' and no accessible extension method 'IsLoaded' accepting a first argument of type 'InterstitialAd' could be found (are you missing a using directive or an assembly reference?)
'InterstitialAd' does not contain a definition for 'LoadAd' and no accessible extension method 'LoadAd' accepting a first argument of type 'InterstitialAd' could be found (are you missing a using directive or an assembly reference?)
Thats it
oh my man, just !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
3 "`" at the beginning and end
Let me guess, you got this code from ChatGPT?
YEAH
ChatGPT produces nonsense code. You'll have to start over, read the actual documentation. It has examples.
I know it has i just cant figure it out
what's up? why when I am trying to react on your message, my screen is shaking and reaction is deleted
I've blocked you
use documentation, yes, https://developers.google.com/admob/unity/quick-start
ask ChatGPT not to write the whole code, but parts of it
oh, I see how now, didn't know that blocks reactions too
Not sure where to ask this but how do I make a liquid
Particle System probably ??
anyone who could tell me what this is?
ask it to write none of it. learn to write the damn code.
it's waiting for the GPU to finish rendering.
you have two (or more) cameras in your scene
I have this code:
for (int i = 0; i < simulationSteps; i++)
{
Gravity.calculateGravity(ghostPlanetsObj, ghostRocketObj, true);
TrajectoryPhysicsScene.Simulate(Time.fixedDeltaTime);
Debug.Log("ghostRocketObj.transform.position: " + ghostRocketObj.transform.position);
lineRenderer.SetPosition(i, ghostRocketObj.transform.position);
}
What I see is that ghostRocketObj.transform.position keeps the same coordonates
calculateGravity make some calculations and ends with AddForce for ghostRocketObj.
public void SeekForPlayer()
{
Vector3 rayOrigin = new Vector3(0.5f, 0.5f, 0f); // center of the screen
float rayLength = 20f;
Ray ray = turretCam.ViewportPointToRay(rayOrigin);
Debug.DrawRay(ray.origin, ray.direction * rayLength, Color.red);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, rayLength))
{
if (hit.collider.tag == "Player")
{
Debug.Log("Did Hit");
}
}
}
So I need to check if the raycast hits something or not.
But whenever I touch the raycast nothing happens? And I have no idea what I did wrong
I see, but why would it do that before I render anything? I don't believe I'm GPU limited at this time
Are you tagged player?
yes
Either the raycast failed to hit anything or whatever it hit was not tagged as player.
Use CompareTag, not equality, to compare tags
Also your ray cast origin should be a world point.
it's fine as is, and is a world point
Ah, ui. Viewport.
It's a ray coming out of the center of the camera
well, it sure looks like you are!
every camera gets rendered every frame
It does work now, but the thing is that the raycast isn't going further than the red line. Even though the maxdistance is a lot
Surely it's just hitting the object your camera is in
The collider is turned off? Then there is nothing to hit on the object
So, print what it's hitting then and find out
Hi there, I need help regarding converting an array of byte into an AudioClip.
I'm building a WebGL app that in runtimes should be able to receive MP3 audio from the website backend where its hosted.
Since its not possibleo to directly send MP3s from website to the app I have to follow this pipeline:
Site generates the mp3 -> converts it into an array of bytes -> converts it into a string -> send it to the app via the SendMessage method.
Now after receiving the string I need to do the opposite, I already did the string to []byte conversion but I'm stuck at creating the audioclip since it indeed create a clip but on play the audio its just a mix of noises. Is somebody able to help?
Here's the script I'm using: https://hatebin.com/drkzqdzrbn
(Before suggesting to use a WebRequest I can't point to a link since the audio is different each time and its generated at runtime)
It does hit the player if I print the gameobject's name. It just doesn't print if i use compare tag to find it.
So then the player doesn't have that tag
AudioClip.Create takes PCM data
i.e. a WAV file
Thanks a lot. This is a mistake on my end 😅.
The one with the red line has the tag, but that is just a empty object.
it's a long list of loudness values
you would need to decode the MP3 data first
i suspect you'll need to grab a third party library for that
trying to interpret MP3 data as a WAV gives you some very weird sound.
Oh ok, any idea on how can I handle Mp3? I dont think I can convert the mp3 data I receive to wav on the go....
yo how i can fix that?
as I just said: you will need a library
So a library that turn []byte into Mp3/Audioclip
ok
Can I look for generic libraries or should I search for unity specific one? Sorry I've never been in this situation
so?
Don't spam. This is a code channel. If you have a question about implementation post a proper question with the code. Read the #854851968446365696 on how to ask questions.
Can directly apply AddForce to an object which is in another scene ?
eg:
private GameObject ghostObj;
...
SceneManager.MoveGameObjectToScene(ghostObj, OtherScene);
...
Rigidbody2D body = ghostObj.GetComponent<Rigidbody2D>();
body.AddForce(forceVector);
I am getting thi error:
NullReferenceException: Object reference not set to an instance of an object
snapToGrid.snap () (at Assets/Script/snapToGrid.cs:42)
ObjectPlacer.Update () (at Assets/Script/ObjectPlacer.cs:95)
ON this line
if (objectPlacer.instantiatedStructure == gameObject)
this is inside a function called snap that is called every frame and I added the following if
if(objectPlacer.instantiatedStructure != null)
{
snap();
}
But didn't fix,
Is also called here in the object placer script in this way:
if (instantiatedStructure != null)
{
instantiatedStructure. GetComponent<snapToGrid>().snap();
}
no, scene are not loaded unless open, but you could store the force with player prefs and give the force when you lead the scene
hi.. would a trigger work if its parent game object has the rigid body componened (the child game object has the trigger and the script that has the on trigger methods)
The parent does not matther, but at least one of the two gameobjects that trigger each other needs to have the rigidbody
I see, thank you
np
How do I ensure that it is loaded ? I use it for trajectory simulation
on void start
thatr void is execture once when you open the scene
in that moment you read the player prefs and add a force
just remember that player prefs don't get deleted even if you uninstall the game, so you need to delete them or set them back to zero when you start the game
Aaah well I do set the scene in the onStart method and it is kept in global
but you're saying that not enought ?
well I added a game object that has a rigidbody component and it didnt work
if i am not wrong script variable get deleted when you laod a new scene, player prefs exist for that reason
the only way to save data between scenes is by actualy saving the data, there are many ways to do it player prefs is an easy one
wait
Here's everything you need to know about saving game data in Unity!
► Go to https://expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.
● Easy Save: https://bit.ly/2BzgdXb
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
·····················································...
I think there is a missunderstanding. In my game scene i create a parallel one for trajectory prediction
this should help
you mean like unity scenes ?
becase i am 99 percent sure that you can't have two scene running at the sae time
wrong
ah my bad
well you learn something new every day
thats why load Additive exists lol
otherwise static data probably
My problem is that I have a GameOject in the TrajectoryScene and I don't know why AddForce doesn't work on it
Oh, huh interesting
ok one question... is there a way to make overlapsphere last for seconds? and have it report all the object that were inside of it
^cast it multiple times
Cast it every frame for x seconds
Bump
hey guys need some help, I am using this code to get me a signed angle on two points the target and the origin, but if the origin rotates the angle changes until the rotation stops
Vector3 targetDirection = target - OriginTargetingAngle.position;
float angle = Vector3.SignedAngle(initialForward, targetDirection,OriginTargetingAngle.right);
float clampedAngle = Mathf.Clamp(angle, -90f, 90f);
what is objectPlacer
A script
What line is 42?
The line i sent
Object placer is null
If object placer .instantiated == gameobject
The script ?
NRE occurs when you attempt to access a member of a null reference.
^
Thats strange because object placer is on a gameobjsct that is ne er deleted
that wont help me a lot but thank you
How would I convert a SceenSpaceReflectionPresetParameter to an int or atleast how do I modify it? I'm using Unity 2014 with BuiltIn.
The reference being null isn't an issue. The error would occur the moment you attempt to access a member.
what is it now ?
Well, that's the solution if you need it ;)
thank you
what i am trying to do is using triggers, i made a box rigidbody, and there's another object that's moving based on its parent's movement.. when the trigger is hitting the box rigidbody, it is not summoning on trigger enter... i dont know why
But in void start i defign objectPlacer = GameObject.Find("Controller").GetComponent<ObjectPlacer>();
}
Make it somehow not null and this error will go away.
Basically I'm trying to modify a Screen Space Reflections preset through a script.
And that script never gets removed
did not answer the question
So the controller object was found but the component wasn't present.
What was the question then?
maybe it never does grab it
debug.log it
Else it would have blown up there first @vague jolt
scroll up and read it
Now i can't try but i will check it more later. At least i know whatto check
Wait
Why the error is not calling on the if in the void update ?
But instead in the if in the void snap. Shouldn't it call before there?
you're checking instantiatedstructure not null
not objectplacer
@vague jolt
You're unable to test print anything so you ought to ask this question later when you're able to debug properly.
Yeah i will do it later
Tanks any way
SceenSpaceReflectionPresetParameter is the parameter used to modify what preset that is being used on Screen Space Reflections
Why doesn't the 1st Log and the 2nd one return the same thing ?
the 2nd Log constantly shows y=1.0000
@north warren don't set quaternion directly
So how to do so
use Euler
First time deaaling with C#, first time using Quaternions
so xyz ?
This ?
you need to find the component it belongs too and get the toggler and see if it's even possible
if thats Global Volume should be fairt simple
Yes never had to deal with Quaternions
First time using Unity, im cloning a project i was previously making using Panda3D
what's with the w component
Oh nvm
actually do mind
you dont new a quaternion method
is a static function
Okay but honestly im still not getting the result im looking for
you should explain what you're trying to do
im making this car game and i want to make the camera follow the car
Child the camera
Hmm...
if you wanna a stiff barely able to adap camera sure
parent it
quick follow.. ok
i can see why it was bought
I'm pretty sure that's something quite simple that I miss but it's driving me insane 🤣
I manage to create the new scene, to move the goshtObjects to it
what is this cinemachine
I can compute physics but I can't apply it
A type of camera
Oh boy
yes but how do i set the follower itself ?
is it some component ? im still fairly new to unity
I've not really seen projects that compute logic between scenes beyond just async loading, so I'm not too aware of computing physics logic like this.
Oh i found smth
I have the feeling that my use case is quite exotic actually 😅
I can't open any project...
this is a code channel. check the logs for relevant info. then ask in a relevant channel if you need further help
okay
also where can I find logs..
can't find them
if only there were some sort of convenient button that would open up the crash logs. since neither of us can read i guess we can assume it doesn't exist
😢
I've been trying for so long
I just installed unity 2022 lts and started having this error in every project and every version
I'm creating a spline like this:
using UnityEngine;
using UnityEngine.Splines;
namespace MCBEAddoner.Nodes
{
public class ConnectionCreator : MonoBehaviour
{
public Transform startMarker;
public Transform endMarker;
public Spline spline;
private void Start()
{
spline = new Spline();
Vector3 startPosition = startMarker.position;
Vector3 endPosition = endMarker.position;
float segX = Mathf.Abs(startPosition.x) + Mathf.Abs(endPosition.x) / 4;
float segY = Mathf.Abs(startPosition.y) + Mathf.Abs(endPosition.y) / 4;
if (startPosition.y < endPosition.y)
segY = -segY;
Vector3 startMiddlePoint = new Vector3(startPosition.x + segX, startPosition.y - segY);
Vector3 endMiddlePoint = new Vector3(endPosition.x - segX, endPosition.y + segY);
spline.Add(new BezierKnot(startPosition));
spline.Add(new BezierKnot(startMiddlePoint));
spline.Add(new BezierKnot(endMiddlePoint));
spline.Add(new BezierKnot(endPosition));
spline.Warmup();
}
}
}
but it doesn't render, why?
https://hatebin.com/uaifbmpagy
This is the code I use to receive an mp3 that was previously converted into an array of bytes and then into a string to be able to enter in a SendMessage()
It works like a charm on unity editor but doesnt work on WebGL, probably due to the limitation to not be able to use 'Application.persistentDataPath' and other local memory related things once hosted on website.
Can somebody help me out figuring out if its possible to convert it?
(posting on this channel cause it is a webgl issue but its mostly a code related thing)
nothing to do with persistentData, everything to do with using file:/// protocol
Oh, thanks for the clarification
So yeah basically I use UnityWebRequestMultimedia to generate the file from the array
I tried with AudioClip.Create but seems that it works for WAVs and not MP3s
oh dang, there you go (:
yes, but these are not useful when the file is not on an url
am I wrong?
you are wrong. you just need to use a different protocol depending on your target platform
For the yaw damping in cinemachine, can you make its range bigger AND its movement slower
right now the more the yaw damping, the more the range AND the movement get bigger
Sorry but can you explain how?
Thanks
https://docs.unity3d.com/ScriptReference/Application-platform.html
if it's WebGL use HTTP or HTTPS if its Editor or PC use file:///
mobile has it's own particular problems because of file security
thats all? wow, I still dont believe it but I'm gonna give it a try rn 
never done any web dev I guess
basically no
It didn't worked :c
This is the suggestion coded, should be fine
"Please note that in WebGL, the use of local file paths such as "file://" + tempFile is only available when running the game from the local file system (file:// protocol). If you plan to deploy the WebGL build on a web server, you need to use UnityWebRequest.Get or UnityWebRequest.Post to fetch the audio data from a server endpoint rather than accessing local files directly."
Could this be? found on chatgpt
Also the request goes fine on editor...
here's the full updated code: https://hatebin.com/lqcbcqdjtc
I really can't understand what should be adjusted :/
hello, this is a bit unrelated but I and trying to develop in VS not using unity just a normal project and whenever I debug the console closes right after compiling the code can anyone help me?
dont cross post..
i already redirected you to the C# discord
No one is responding
you didnt even wait 2 minutes
also Console applications close after runs
unless you put Console.ReadLine() at the end
also the last message in that server was 3 hrs
or you hold the app inside a while loop
I know but is there a permeant solution?
anyways thanks for your help
Does Assembly-CSharp.dll not exist in the latest version of unity 2021?
I've reinstalled twice already and I can't get rid of this error on an old project even when moving the assets to a new one
keep the backup.
delete library folder
try again
wait for rebuild
This time these files were generated, but not the dll
@knotty sun sorry for the ping man, when you have time please check the reply. 🙏
anyone here has a tutorial for a zoomable panel?
just search for it in youtube
I'm gonna need to use Netcode for Entities for a project of mine and so I'm trying it out on a local project, but the out-of-the-box project (2D URP+Entities, Entities Graphics and Netcode For Entities in 2022.3.1f1) already came with a memory leak warning which I ignored and started following a tutorial on Netcode For Entities hoping it would disappear. Not only it didn't disappear but there are now even more memory leaks.
The video I'm following is this one: https://www.youtube.com/watch?v=WlWDus1h5YE
I followed the video all the way to the end and I have the same as him, but if you don't want to watch it, this is the code I have rn:
NetcodeBootstrap.cs
using Unity.NetCode;
using UnityEngine.Scripting;
[Preserve]
public class NetcodeBootstrap : ClientServerBootstrap
{
public override bool Initialize(string defaultWorldName)
{
AutoConnectPort = 2134;
return base.Initialize(defaultWorldName);
}
}
GoInGameSystem.cs
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.NetCode;
using UnityEngine;
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation | WorldSystemFilterFlags.ThinClientSimulation)]
public partial struct GoInGameClientSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
EntityQueryBuilder builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll<NetworkId>()
.WithNone<NetworkStreamInGame>();
state.RequireForUpdate(state.GetEntityQuery(builder));
}
[BurstCompile]
public void OnDestroy(ref SystemState state)
{
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
EntityCommandBuffer commandBuffer = new EntityCommandBuffer(Allocator.Temp);
foreach ((RefRO<NetworkId> id, Entity entity) in SystemAPI.Query<RefRO<NetworkId>>().WithEntityAccess().WithNone<NetworkStreamInGame>())
{
commandBuffer.AddComponent<NetworkStreamInGame>(entity);
Entity req = commandBuffer.CreateEntity();
commandBuffer.AddComponent<GoInGameRPC>(req);
commandBuffer.AddComponent(req, new SendRpcCommandRequest { TargetConnection = entity });
}
commandBuffer.Playback(state.EntityManager);
}
}
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct GoInGameServerSystem : ISystem
{
public ComponentLookup<NetworkId> NetworkId;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
EntityQueryBuilder builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll<GoInGameRPC>()
.WithAll<ReceiveRpcCommandRequest>();
state.RequireForUpdate(state.GetEntityQuery(builder));
NetworkId = state.GetComponentLookup<NetworkId>(true);
}
[BurstCompile]
public void OnDestroy(ref SystemState state)
{
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
FixedString128Bytes worldName = state.WorldUnmanaged.Name;
EntityCommandBuffer commandBuffer = new EntityCommandBuffer(Allocator.Temp);
NetworkId.Update(ref state);
foreach ((RefRO<ReceiveRpcCommandRequest> reqSrc, Entity recEntity) in SystemAPI.Query<RefRO<ReceiveRpcCommandRequest>>().WithAll<GoInGameRPC>().WithEntityAccess())
{
commandBuffer.AddComponent<NetworkStreamInGame>(reqSrc.ValueRO.SourceConnection);
NetworkId networkId = NetworkId[reqSrc.ValueRO.SourceConnection];
Debug.Log($"{worldName} connecting {networkId.Value}");
commandBuffer.DestroyEntity(recEntity);
}
commandBuffer.Playback(state.EntityManager);
}
}
the problem is that if i instantiate UI elements after resizing, they will stay the same size
is it UI Toolkit?
When using UI Toolkit, you have to specify that you want to update a certain element, I don't think the same applies to the default UI elements
that i want to update a specific element?
yeah
the same size as before or after resizing?
I added something that I had missed on the video and now I have less memory leaks, but I still have the ones the popped up since I created the project
Managed to force Assembly-CSharp.dll to generate (seeminly by making a new empty c# script)... but it's still failing to produce update.txt
idk, you should safe resized value somewhere
probably in PlayerPrefs or json if you gonna e.g. move scenes or whatever
What's the best way to make a multiplayer physics based game sync properly? It's turn based to latency isn't much of a problem, but collisions look either goofy because of interpolation or choppy when I use network transform. I am using normal physics rn but its not deterministic so the server sync is really visible which I don't really want
Using Netcode for GameObjects
Could be some fighting with ownership between client and server, but yeah #archived-networking
Ah, thanks for the redirection
What might be a good way to handle logging with an object pool? (and by "good" I mean least I/O work without missing logs) Would it make sense to use a StreamWriter thats always open for the duration of the game and periodically writes a batch of logs, or on every single new entry or when the pool recycles the oldest entry? Should I make a new streamwriter and close any previous for every log? Or would there be a better approach in general? For context, im working on a logging system for a Windows build so I can see Debug.Log happen in game and when certain events trigger, so sometimes it could be writing logs every frame or sometimes just a few every so-often
I have many game object with a script inside, thats script is called snapToGrid, if i get the reference of one gameObject and get his component and do snapGrid.snap(); is the function snap called only for that gameobjct script ?
it's called on the object you called it on
When you paint your house you are not painting every house in existence.
When you fill your car with gas, you are not filling every car in the world with gas
yeah but unity is not as straight forward as paiting houses
it is
arguable
When you understand it it is
Object oriented programming is just that
there's an object
you are calling a method on the object
not on the concept of a SnapToGrid
but that particular SnapToGrid
because i am getting this error
NullReferenceException: Object reference not set to an instance of an object
snapToGrid.snap () (at Assets/Script/snapToGrid.cs:43)
ObjectPlacer.Update () (at Assets/Script/ObjectPlacer.cs:97)
And i don't get why
A variable you are dereferencing on line 43 of snapToGrid.cs is null
show your full script
is this snapToGrid line 43?
Or is this ObjectPlacer line 97
I think it's ObjectPlacer line 97
sure
this is the script with the function
https://github.com/starlinetor/Factorio-Logic-Simulator/blob/main/Assets/Script/snapToGrid.cs
if (objectPlacer.instantiatedStructure == gameObject)
this is the script caling the function
https://github.com/starlinetor/Factorio-Logic-Simulator/blob/main/Assets/Script/SaveFileGenerator.cs
this is line 43
so objectPlacer is null
irrelevant
objectPlacer is null
not gameObject
but i never disable the script
how can it be null
it was either never assigned, or it was assigned to null
void Start()
{
insideX = (x % 2) / 2f;
insideY = (y % 2) / 2f;
outsideX = -insideX;
outsideY = -insideY;
objectPlacer = GameObject.Find("Controller").GetComponent<ObjectPlacer>();
}
here is clearly declared
that's not a declaration that's an assignment
And the right side of that can be null
GameObject.Find("Controller") could return null
and so can GetComponent<ObjectPlacer>()
yes but the script works, is just when the gameobject is instanted that it returns the error, than it works as intended
Either you don't have an active object in the scene named "Controller", or that object does not have the ObjectPlacer component on it
which GameObject? This is vague.
show the full stack trace of your error
it could also be you are calling the snap() function before Start runs
that could be
this is not the error
click on the error
to see the full stack trace at the bottom
NullReferenceException: Object reference not set to an instance of an object
snapToGrid.snap () (at Assets/Script/snapToGrid.cs:43)
ObjectPlacer.Update () (at Assets/Script/ObjectPlacer.cs:97)
so where is ObjectPlacer getting the snapToGrid reference from?
this is problably the problem, how i check if start runned?
show the ObjectPlacer script
no I don't think this is the problem based on the fact that it's happening every frame
sorry i sent before the wrong script
I think you're ah yes ok
this is definitely the proble,m
you're calling snap right after you instantiate it
that will be well before Start() runs
makes sence
Simple fix here is take this:
void Start()
{
insideX = (x % 2) / 2f;
insideY = (y % 2) / 2f;
outsideX = -insideX;
outsideY = -insideY;
objectPlacer = GameObject.Find("Controller").GetComponent<ObjectPlacer>();
}```
and just rename that to Awake()
whats the difference ?
Awake will have run already by the time Instantiate returns
it runs as the object is created
Awake happens before start. Like... awake happens on all existing objects first, before start runs on anything afaik. And then Update.
To be honest I would probably also just remove this:
//before placing the structure is important to make it snap so we are sure that is actually placed
if (instantiatedStructure != null)
{
instantiatedStructure. GetComponent<snapToGrid>().snap();
}```
and put this in snapToGrid:
```cs
void OnEnable() {
snap();
}```
not that is needed because when i place the structure it needs to do the math for collision
my code is horrible so i am using the actuall transform.position and it happened that the game object was not snaped before
so it would mess every thing up
so i just run snap before placing it
Hi there, I am currently trying to implement photon into my openxr project and I have the head linked up, however my hands are in the wrong position and rotation. The hands with the prefab and my xr hands are also rotationally and positionally aligned to each other. Here is my scrpt to set the positions:
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;
public class NetworkPlayer : MonoBehaviour
{
[SerializeField] private Transform head;
[SerializeField] private Transform leftHand;
[SerializeField] private Transform rightHand;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
MapPosition(head, XRNode.Head);
MapPosition(leftHand, XRNode.LeftHand);
MapPosition(rightHand, XRNode.RightHand);
}
void MapPosition(Transform target, XRNode node)
{
InputDevices.GetDeviceAtXRNode(node).TryGetFeatureValue(CommonUsages.devicePosition, out Vector3 position);
InputDevices.GetDeviceAtXRNode(node).TryGetFeatureValue(CommonUsages.deviceRotation, out Quaternion rotation);
target.position = position;
target.rotation = rotation;
}
}`
Are you saying there's a networking problem here, or you have a problem getting the hands aligned to the VR controllers?
Its just to do with the hand alignment
All of the positions in the unity editor are at 0,0, as shown by the second image
in the editor they are fine
huh?
is there a difference between "editor" and "unity editor"?
it's unclear which image is the "correct" thing and which is wrong
and what photon has to do with it
you should start by just looking at the hand GameObject in scnee view with tool handle rotation set to Local first
to make sure the object itself is oriented properly
perhaps your 3D model is imported incorrectly for example
it is the same 3d model, how do I set the gameobject to local?
set tool handle rotation to local by selecting it in the scene view overlays
or pressing X to toggle between local and global
assuming thats what you mean by "set the gameobject to local?"
btw to be more clear on the right hand image, the left hand is the xr hand and the right is the photon prefab hands, its just showing that the rotations are the same in both. the left image is showing how the rotation in the photon hand is dramatically different to the rotation in the xr hand, despite them having the same rotation before i press start game
I am just saying I dont think it is a problem with how the prefab and xr components are set up, more to do with how they are alligned together in the code
I am attempting to allow my game to register if there is a controller connected, or if there isn't to just use keyboard inputs. But the controller connects, disconnects, then reconnects, but no input from the controller is registered. If I unplug the controller it still registers as connected, but I can still control it from keyboard, unlike what I wish to do which is disable keyboard inputs in the game when a controller is plugged in.
I am using the unity manual code for detecting controllers as seen below
IEnumerator CheckForControllers() {
while (true)
{
var controllers = Input.GetJoystickNames();
if (!connected && controllers.Length > 0)
{
connected = true;
Debug.Log("Connected");
} else if (connected && controllers.Length == 0)
{
connected = false;
Debug.Log("Disconnected");
}
yield return new WaitForSeconds(1f);
}
}
and this is my code for registering inputs
private void OnEnable()
{
if (playerControls == null)
{
playerControls = new PlayerControls();
if (connected == true)
{
playerControls.PlayerMovement.Movement.performed += i => movementInput = i.ReadValue<Vector2>();
playerControls.PlayerCamera.Movement.performed += i => cameraInput = i.ReadValue<Vector2>();
}
else if (connected == false)
{
playerControls.PlayerMovementKeyboard.Movement.performed += i => movementInput = i.ReadValue<Vector2>();
playerControls.PlayerCameraKeyboard.Movement.performed += i => cameraInput = i.ReadValue<Vector2>();
}
};
playerControls.Enable();
}
please help
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
How do I compute a renderingLayerMask? I don't see any obvious equivalent to LayerMask.GetMask().
https://docs.unity3d.com/ScriptReference/Renderer-renderingLayerMask.html
i can just OR together some bitshifted stuff, but it's kinda gross
Help me please
btw you can just set parent inside the instatiate method
is that actually the correct line number? it looks fine
it would be a problem if you were doing MapZone.transform.SetParent
this is only happening in playmode yes?
I think you're setting the prefab parent and not the actual instantiated MapZonep
are you perhaps calling the createleftMap method on a prefab?
Ah, that would do it.
https://paste.ofcode.org/sHyTXzdL6hPfwF2XFL2KY3
I have the following code where in the start screen(containing text), the user presses on the screen "tap to start" to begin the game. Once this happens, I want to instantiate all the objects with the tag of "Dot" with a 1 second interval. If the player presses the wrong dot, they die, and a tap to restart screen shows up, resetting the entire scene.
Problem: when the player dies, i want the tap to restart screen to stay there until the user taps on the screen again to restart. Right now, once the player dies, the scene gets reloaded immediately and the restart text doesn't show up
use the coroutine you have
right now it's not doing anything
the coroutine is instantiating the dots with a one second interval
that coroutine is literally doing nothing
it waits 1 second once it runs but doesn't actually do anything after 1 sec
coroutines run async they wont pause the method you ran it from
unless it was a coroutine as well and using yield
you're just creating a new routine each dots iteration
but its empty
oh how would I fix that?
don't put it in a loop first of all so you 're not just creating a bunch
IEnumerator DotTimeGap()
{
yield return new WaitForSeconds(1.0f);
//Logic that needs to wait 1 second
//SumMethod();
}```
if you want a continuous running thing then use a while loop
@potent sleet I've tried to set the MapZonep = Instantiate(MapZone,position*2, Quaternion.identity,transform);
and now i get another error:
Cannot instantiate objects with a parent which is persistent. New object will be created without a parent.
And yes the error occur only on playmode.
@somber nacelle It has the same issue
Sorry for the late response but I've tried to find solutions.If i dont set any parent to the object I won't get errors , but the instantiation won't have any parent,and that's wrong in my case.
yeah you are 100% calling the method on a prefab. you need to get a reference to the instance of the component that has the createleftMap method on it, then call the method on that instead of on a prefab
show the code where you are calling that method. please share the entire class in a bin site !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I have a question about materials and shaders
Anyone has time for help?
first: https://dontasktoask.com/
second: this is a code channel
Wait in which Channel do i have to ask a question about Mats?
#🔎┃find-a-channel has a list of all channels and their purposes
oh thx ^^ n sry for dat
should i make a voxel engine via using a 2D array noiseMap and then evaluating the height based on an AnimationCurve
OR
use an array that gets all dimensions of the map via noise and then store that
OR
should I use the first for the surface and the latter for the underground
hmmm the restart issue still seems to persist. I think it's because the user taps on the dot, that touch is considered to be Touch.End, causing the scene to reload and the restartText to not appear
I was just poointing out something, I didnt see the any of the Tap parts
So when the user presses on a "bad" dot, the restart text doesnt show up at all
how can I search for a word in a json file?
ah
what editor r u using
yo im new to coding and game development and i might have a few dumb questions to ask if any1 could help lmao
in code or with an app ?
in code while game is running
can you show/describe the issue a bit beter im confused on what u asked
i want to know if there is some data exist or not, if not make some default data
maybe read the json text and search the string
File.ReadAllText
iirc
or ReadAllLines
so basically I "tap to start" the game, once I do, the dots instantiate with a one second delay, the user has to press on the "good" dots. If the user presses on a "bad dot", a "tap to restart" text shows up. Once the user taps the screen to restart, the original scene reloads - so they can "tap to start" again. However, if I press on a "bad" dot, the restartText doesn't show up, and the scene ends up reloading
it's something to do with the Touch.End and Touch.Began but I can't find a solution
basicly i want to know is it the first time game run by the player or not?
is there an easyer way instead of checking the json file?
put the load scene in a delay with coroutine
put a bool so user can no longer click or anything after coroutine has initiated
are you shipping the json file with the rest of the game files? if not then the file not existing will tell you whether it may or may not be the first time it was run. otherwise you can add whatever default value you'd like into the json file you ship
ok thanks
remmeber any method/thing you want delayed always goes AFTER the WaitForSeconds part
im not shiping the json file, its my save json file. I wrote a function that need some data from the json file to work, but if run the game for the first time that data wont be exist
exactly that data won't exist. so you just create it with the default data you want. literally just check if the file already exists, if not then you know it doesn't exist and needs the default value or whatever it is you're doing
so I have a script to handle all the save and loading stuff, should I make the default vales there? cuz there i have a line that check if the dir is exicts or not, if not it will make one, maybe i can just use that if statement to config the default data
sure, that's one way to do it. yeah
thanks a lot
sorry to bother
this is my json file after the first run:
{
"Data1": {
"highScore": 1,
"coin": 0
},
"Data2": {
"selectedCube": 0,
"cubeList": []
}
}
I want that cubeList to have some values in it, some bool values. the default values are true, false, false etc. is there a way to config that so I can have those values like other variables
instead of going that way that i change the json file in the first run
it looks like either an array or list. so when you create the instance of the object you just create the array or list and fill it with your desired values. you do this before you serialize the object to json
you mean where i create the array if list in the first place?
probably? i don't really have the full context so i couldn't say for sure
i would personally just do it in the object's parameterless constructor (assuming this is a class not a struct)
Awake then OnEnable are called immediately upon instantiation in that order, Start happens later
i do hope that question was unrelated to (de)serializing json since you shouldn't be serializing monobehaviours
thanks
Im serializing some data like score and stuff that are in the GameManager script, all other sava load system are in non mono behaviours scripts
Is it wrong?
depends, are you creating some other object that contains the data you are serializing or are you actually serializing the GameManager class itself?
I have a struct in gamemanager script, Im serializing that
I make a new Objet out of that, save data in it and serialize it
If it effect on performance i dont really care cuz the project is not that big and this would be my first project with proper save load system
ah lovely then you can't even use a parameterless ctor for it. why not make it a class instead?
i mad a big mistake judging by the "lovely"
To explain a bit, the way that waitforseconds works is that as the game reads code line by line (oversimplification maybe but ye) it will stop at that pause part until enough time passes, then runs stuff below.
It doesn't like... pause everything in that script.
So you'd probably want something to happen after that pause ends.
Hey so I'm noticing that as a default (no material), unity will render both the front and back faces of quads/sprites. Is there a way to change this behaviour?
Or specify to certain sprites to only render backface/frontface?
i mean you're doing it right by (de)serializing a plain c# object, but the way you've got it set up is you'd need some other object to construct all of your default data and pass it to the object when it is created (either via parameterized ctor, or by manually assigning each property after calling the ctor). This is just fine if that's how you want to do it, i personally would prefer to just set up the default data for the object in its own parameterless ctor which would require it being a class since unity doesn't support c# 10 yet
Library\PackageCache\com.unity.2d.common@7.0.2\Path\Editor\EditorTool\PathEditorTool.cs(108,30): error CS0115: 'PathEditorTool<T>.gridSnapEnabled': no suitable method found to override
I started my unity project and i ghot this error
thanks for your explaintions, to be perfectly honest i dont know what is parameterless ctor, I guess i will just stick tomy solution for this project but i will defently look into what you just explained.
i think i got it
i opened the game using an older version
it's a constructor with no parameters
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors
Can't wait for dots raycast tutorial
how can i find a word in a string of words?
find it as in check if it exists, find its index, or something else?
find if its exits or not and returns a bool
String.Contains() should be fine then
public void save()
{
if(loadSaving == true)
{
return;
}
loadSaving = true;
string save = JsonUtility.ToJson(saveJSON, true);
File.WriteAllText(Application.dataPath + "/save.json", save);
loadSaving = false;
}
GameObject structure;
public void laod()
{
if (loadSaving == true)
{
return;
}
loadSaving = true;
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
//read save file
string save = File.ReadAllText(Application.dataPath + "/save.json");
SaveJSON loadSave = JsonUtility.FromJson<SaveJSON>(save);
for(int i = 0; i<loadSave.entities.Length; i++)
{
foreach(GameObject prefab in prefabs)
{
if (prefab.tag == loadSave.entities[i].name)
{
structure = Instantiate(prefab.gameObject);
}
}
structure.transform.parent = transform;
structure.transform.position = new Vector2((float)loadSave.entities[i].position.x, (float)loadSave.entities[i].position.y);
structure.GetComponent<RotateSprite>().rotation = loadSave.entities[i].direction;
}
saveFile();
loadSaving = false;
}
THese two function save and load, but if you press the two buttons fast enoght all the entitities accumulate, what can i do to prevent it ? my bool state checking does not work..
thanks
the bool does not work because its set true, logic happens, then its set false. the other function will not run async unless you have extra code hiding somewhere
i actually found that there is another bug
im not entirely sure what "entitities accumulate" means
i save 5 and then there are 10, but is afctually another problem causing that
not pressing fast
how can I give value to a bool[] when its created? I mean when I craete it with this code:
public bool[] cubeList;
like this which we give value to a int:
public int number = 10;
is there any known bug in Unity that produces white screens on nvidia gpus:?
seems to only render overlay uis
ok so the problem is the following, when i load the save file first i delete all the structure, then i place the new one based on the save file and then lastly i call a function that stores all the instantiated structrue in a list. The problem for some reason is that it does not remove the reference to the old structures, I know it should work because the same function is called when i destroy or place structreu but does not work when is called by the function load.
Save file generator, where the laod and save functions are, there are two save function, one to file one to the list
https://github.com/starlinetor/Factorio-Logic-Simulator/blob/main/Assets/Script/SaveFileGenerator.cs
Place structrue, here the save to list function is called right (saveFile(), sorry for terrible and confusing name)
https://github.com/starlinetor/Factorio-Logic-Simulator/blob/main/Assets/Script/ObjectPlacer.cs
Destroy strcutures, here the function is also called right
https://github.com/starlinetor/Factorio-Logic-Simulator/blob/main/Assets/Script/DeleteOnRightClick.cs
The immage is what it looks like after load is called
either new bool[numberOfInidices] which creates an array of bools all set to false (since that is a bool's default value) or you could use a collection initializer to create the array with specific values
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
or if you create the array in the constructor for the object (assuming this is still for the object you are serializing to json) you can use a for loop after instantiating the array and assign values
that question implies you have no idea what an array is
thanks all
like if a place or add a structure the function is called correctly and the old reference are removed
then you cleared the wrong list, or at a wrong time, or on the wrong object
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
This is how i destroy all the childs, is this working even if is called using abutton ?
again, they are destroyed
you didnt clear the list that you show in your screenshot
a list wont magically know to remove destroyed objects
GameObject.Find("Structures").GetComponent<SaveFileGenerator>().saveFile();
This is called at the end of the load , this is after they are deleted
first thing the saveFile functon does is
Debug.Log("Saving");
saving = true;
structures.Clear();
I get it something is wrong here but where
this solved an issue that ive been wasting time on it for like 2 hours
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
//read save file
string save = File.ReadAllText(Application.dataPath + "/save.json");
SaveJSON loadSave = JsonUtility.FromJson<SaveJSON>(save);
for(int i = 0; i<loadSave.entities.Length; i++)
{
foreach(GameObject prefab in prefabs)
{
if (prefab.tag == loadSave.entities[i].name)
{
structure = Instantiate(prefab.gameObject);
}
}
structure.transform.parent = transform;
structure.transform.position = new Vector2((float)loadSave.entities[i].position.x, (float)loadSave.entities[i].position.y);
structure.GetComponent<RotateSprite>().rotation = loadSave.entities[i].direction;
}
GameObject.Find("Structures").GetComponent<SaveFileGenerator>().saveFile();
Yes but it should wait for all the childs to be destroyed then go for instantiating the new one and then update the list
I forced it to run on AMD integrated graphics and it works; apparently it doesn't work on nvidia at all, I've tested 4 systems
unless it does not wait to destroy them
doing thisn
foreach (Transform child in transform)
{
Destroy(child.gameObject);
GameObject.Find("Structures").GetComponent<SaveFileGenerator>().saveFile();
}
does not change anything
you are doing random actions
that functions when claled as the first thing it does is clear the list
I was right
Destroy does not stop the stack
it waits for the end of the frame
meaning that all the code was exected before the game objectrs were destroyed
correct, Destroy only queues the objects for destruction at the end of the frame. not only that but destroyed objects are not automatically removed from lists, you do have to do that yourself somewhere
i changed to DestroyImmediate and now they don't appear in the list anymore
you sure they get removed by default because my problem was exactly that
do not use DestroyImmediate for this either
https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html
This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code you should use Object.Destroy instead. Destroy is always delayed (but executed within the same frame).
But they say that you should not use that function so you know a better solution ?
Destroy has no idea what lists contain the object
just use Destroy and make sure to remove the destroyed objects from the list
I just directly clear the list at this point i guess
yes destroy is deferred til the end of frame, but you dont have to wait for it
Ahh know i got it
from the moment you marked the object for destruction you can safely assume its gone
for most cases
ok ok my bad i didn't get what you meant
i did this:
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
yield return 0;
is this fine ? so iam sure that the gameobject are gone and i can save normaly.
not sure what the goal is, but just yield return null; instead for the frame
the idea is i wait 1 frame so the objects are gone
wait for what though? is there code after this
yes
this
this still wont affect your list
yield return 0 should be yield return null if you want to wait a frame.
done
is there a problem with return 0 ?
just for curiosity
it seems like a thing you just made up
hi all 👋 just wondering if anyone has advice on how to find talented freelance unity multiplayer devs. i saw #📖┃code-of-conduct redirects to official unity forums, but honestly those posts (and their responses) are uninspiring
we're a VC-backed startup and have the capital, building out some really interesting stuff
this is for asking about code second use fiver
scrolling down, people say null in that same thread further below. But either way i dont think this is what you really want to do
because now all the game objects are just null, but the list still hasnt changed
my project is like 87% duck tape and glue, i am a terrible programmer 🙂
I am not sure why they would suggest that, it's not in any of the docs. It would require the int to be boxed, which means it allocates, unlike yielding for null
don't know is just the first thing i saw and it worked.
fiverr quality can vary widely, we're looking for more proven talent and paying more for the right collaboration
which channel here on discord is more appropriate for getting this advice?
but indeed null makes more sence
This is for aksing about code help not this kind of stuff
just kidding
i am stupid
i just read the description
Advertise on linkedin, discords that allow it, especially ones that are based in your local area. Make yourself known to the local development scene and find resources through them. Random posts on huge platforms is not a great way to find people with any sense of quality or reliability.
thanks @quartz folio for the record i'm not trying to find someone here, but rather getting advice from engineers here who know of the best channels through first hand experience
for instance, if you told me "Unity job forums are shit, nobody good checks those" then that would be valuable info
Nobody checks the forums, nobody checks large nebulous platforms
realistically you'll want people to apply for your posting (not on the forums, like linkedin as vertx said), rather than looking through forums for individuals. Assuming this is an actual position
I know netcode front and back. I can write your company a AAA quality netcode engine for unity from scratch. We're not supposed to advertise in these channels, so you can DM me if you're interested.
Continue this in #💻┃unity-talk seeing as it's cross-posted there anyway (please do not crosspost).
thanks @lean sail i am pretty unconventional, and prefer to seek out the talent rather than sift through people applying to our job post. i have moved the discussion to #💻┃unity-talk because i'm guessing that's the more appropriate channel
tysm all 🙏
i originally posted here, realizing it was the sub-optimal place. happy to delet msgs
It's fine, just continue the convo there if anyone wants to, but it's pretty much been answered imo
If anyone wonder how I did it
also this is a pretty poor workaround for an issue that is easily solvable by getting a reference to the correct object
any of you lads have advice on how i can create an object moving system where i can pick up objects without them clipping through other objects, or spazzing out when touching another object? i have an idea on how i can have it keep a target position and keep it's rotation relative to the camera, but i don't know how to go about working with collision.
my research has mentioned i need to use velocity with rigidbody physics, but i don't understand how to implement that. the closest example i could find was a little difficult to follow
Hi, I am going to use unity iap for the first time. I heard that the codeless IAP is broken, is that right? so i have to implement the iap via coding?
unity should handle that by defualt, just add a rigid body and a collider to the game objects. The only important thing is that you need to move what you want to have physics using velocity or forces and not by just chaning the transform position
there are many setting depending what you want to do but it should still work out of the box even if not in a hoptimal way
you'll still run into issues with it spazzing out if you do that, especially if you are trying to keep the object at a target position
This depends on the game mechanics, you cant have the object not clip through objects, touch other objects (collisions), and be kept at a target position 100% of the time, this is contradictory.
Do you want there to be collision even?
i do. my objective is to have it try to correct itself to a target position & rotation, while getting altered by anything that gets between them, such as picking up a book and trying to drag it on a table, but getting hung up on an immovable object
and then i reckon if the distance to correct is too high it will just stop trying and fall, and then the selection will be null, but i can figure out that part myself
what about something like procedural animations ?
Im not sure if others do this but you might be able to use a spring joint for this. Otherwise just use a collider and rigidbody with no gravity and try to always move it towards the target position. That way its more of a flying object.
you keep the actuall object in a fixed position and then move the sprite around to not clip
or you could use forces to keep it in place, this way the object would not clip because if a force makes it collide on a structure the force does nothing, it would also look a bit more realistic maiby
separating the actual object and visual sounds horrible for this..
honestly i dont know what you mean to use animations for this
i’m not using sprites anyways. this is being done in 3D
i mean the thing you render
sorry i just use 2d i don't know the name for 3d
like what you want to do is something like slime rancher ?
lol all good. appreciate the suggestion regardless
like the gun that sucks stuff and keeps it there ?
is there a function to do that? like TryMoveTowards or something?
it’s more comparable to the game Amnesia or Gmod
If you're trying to replicate a garry's mod physics gun, then you should be modifying rigidbody velocity to move the grabbed object wherever it needs to go
this could help maiby
https://discussions.unity.com/t/prevent-grabbed-object-from-clipping/215285
for the rigidbody? you can add force
or do you mean the joint?
i already suggested what the comment says
or another thing you could do is the same that some fps do for guns
you render the cube separated from the world in such a way that it does not appear to clip
that's still going to look very weird
even if is tecnically clipping
you could use perspective rules to scale it when it clips so it does not look to weird?
thats going to be really annoying to setup, especially since they want it to be colliding with objects so its not* going to be clipping with rigidbodies
The best way is to just to simply point the velocity wherever it needs to go
I'm almost certain this is how gmod does it anyways
it can be created with a basic damper system. Far away from the point? More velocity. Close to point? Less velocity
thats also why i suggested spring joints, but maybe spring joint would have unintended results
like if it goes out of bounds, the force might go really high
i feel like burt idea of just moving ity with a force/velocity to a fixed point seems the easiset to implement
🤔 i did also say that while u were suggesting random solutions
either i suppose, i was more referring to a rigid body tho
my bad
you should experiment with rigidbody and addForce(). its really something you need to see to understand in how it moves
ohhh you sure can determine the direction with addforce can’t you
you add a force in a direction yes, which changes the objects velocity. The forcemode* you use will have a different effect
period. that might be just what i need to look at. i’m so slow i’ve been struggling with that concept for days and it’s like a day one function that i forgot 😩
You would get better results manually modifying the velocity
if you want something snappy
does anyone know how I can make it so that when i switch cameras, the player doesn't doesn't like whip around? What i mean is, when the player is in the free look camera mode and the camera and player model are facing in oposite directions. then when the player switches to the backview, the player model faces where the free look camera was facing before
just ask your question here, no ones gonna give 1 on 1 lessons for free
@lean sail @void basalt just came back to say thanks for the input. y'all both pointed me in the right direction and i'm much closer to getting what i want now
asking questions is how you learn lad
re-read my message lol, just because u want to learn doesnt mean ppl will teach u for free
This is how my character looks (the 2 rectangles above are the leg formed from 2 parts. I will multiply the leg after I finish this). How can I add bones to this?
you should look at a tutorial for this, this also isnt a code question
it should be called "2d rigging"
I tried to look for a tutorial like this but they all are using sprites. I am using only game objects. Sorry about the code part.
sprites are GameObjects . . .
a SpriteRenderer is a component attached to a GameObject. it has a sprite property where a 2d sprite is placed . . .
Could I get some help with this
my hand Model is supposed to look like this when I pick up a Thompson Mag but when I try to pick it up it looks like
That is with my hand just normally straight
and once I let go it goes back to normal
I hope you like math
https://math.stackexchange.com/questions/1611308/best-fit-line-with-3d-points
Python code: https://stackoverflow.com/questions/2298390/fitting-a-line-in-3d
Okay, I need to develop an alorithm to take a collection of 3d points with x,y,and z components and find a line of best fit. I found a commonly referenced item from Geometric Tools but there doesn't
linear regression
the math really isnt hard, considering its all solved already. Just a matter of taking the algorithm
There should be a math function that makes a slope like that on graph, use it and add random range...
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
{
// Calculate the centroid of the dots
Vector3 centroid = Vector3.zero;
foreach (Vector3 dot in dotsList)
{
centroid += dot;
}
centroid /= dotsList.Count;
// Calculate the sums of products for the covariance matrix
float sumXX = 0f;
float sumXY = 0f;
float sumXZ = 0f;
float sumYY = 0f;
float sumYZ = 0f;
foreach (Vector3 dot in dotsList)
{
Vector3 deviation = dot - centroid;
sumXX += deviation.x * deviation.x;
sumXY += deviation.x * deviation.y;
sumXZ += deviation.x * deviation.z;
sumYY += deviation.y * deviation.y;
sumYZ += deviation.y * deviation.z;
}
// Calculate the covariance matrix
Matrix4x4 covarianceMatrix = new Matrix4x4(
new Vector4(sumXX, sumXY, sumXZ, 0),
new Vector4(sumXY, sumYY, sumYZ, 0),
new Vector4(sumXZ, sumYZ, dotsList.Count, 0),
new Vector4(0, 0, 0, 1)
);
// Calculate the eigenvalues and eigenvectors of the covariance matrix
covarianceMatrix = covarianceMatrix.inverse;
Vector3 eigenvalues;
Matrix4x4 eigenvectors;
covarianceMatrix.Diagonalize(out eigenvalues, out eigenvectors);
// The eigenvector with the smallest eigenvalue represents the direction of the best-fit line
Vector3 bestFitDirection = eigenvectors.GetColumn(0);
// The centroid represents a point on the best-fit line
Vector3 bestFitPoint = centroid;
// Now you can use the bestFitDirection and bestFitPoint to visualize or further utilize the best-fit line
Debug.DrawLine(bestFitPoint - bestFitDirection * 100f, bestFitPoint + bestFitDirection * 100f, Color.red, 10f);
}```
linear regression will give you the line that fits input points..
Just populate with your list of 3d points
I meant something like this http://www.bristol.ac.uk/cmm/learning/videos/random-slopes.html
But lot simplistic
but like this
did u write that up yourself?
oh..i was gonna say i was impressed someone could be confident in their lin alg skills this much
dont worry i did lin alg for 4 years in uni and i still couldnt tell u
I take lin alg next semester so maybe I'll understand a portion of it
well i understood it, then upper year courses made it more complicated
i already forgot all topics on stats i studied
quick question which i'm sure if obvious to those who know, i'm playing around with unity to learn and i'm working on learning raycasts, and my current issue is that dispite my best attempts, it doesn't seem to be registering:
void JumpStart(InputAction.CallbackContext value)
{
Debug.Log("Jump Pressed!");
RaycastHit hit;
if (Physics.Raycast(
transform.position,
scanDirection,
out hit,
jumpScanDistance,
0
))
{
Debug.Log("Did Hit");
if(hit.transform.tag == "ground") {
Debug.DrawRay(
transform.position,
scanDirection,
Color.green,
5
);
}
else
{
Debug.DrawRay(
transform.position,
scanDirection,
Color.cyan,
5
);
}
Debug.Log("Raycasted");
}
else
{
Debug.Log("Did not Hit");
Debug.DrawRay(
transform.position,
scanDirection,
Color.blue,
5
);
Debug.Log("Raycasted");
}
}
You know that something is not easy to understand when the people who use it don't find a better translation than half-german. ( eigenvalue /eigenvector )
do you know what 0 is doing in your raycast?
(i know, just seeing if they know)
oops
is is the layer mask, i currently have it sent to 0, which is what the checkered ground below it is set too
aka, da default lol
double check i guess if your ground is really on default, and visualize how far the ray is going by doing
Debug.DrawRay(transform.position, scanDirection * jumpScanDistance, Color.green, 5);
That's not a layer mask https://unity.huh.how/programming/raycasting/layer-masks
corrent, i meant the index for the layermask because it only takes in an int as an argument
at least from what jetbrains is telling me lol
Please just read my resource so you understand what a layermask is
no green either with the test for whatever reason
i totally get you/ that, i'm reffing to the unity docs which use a bitshifted int for their input here:
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
and what of it? You're using 0
maybe i'm missing something, but yee
0 should work if its the default layer right? although i agree still should setup the layer properly
im dumb, its 3am dont judge me
yes, because i'm using my own layers, to my knowledge and what i see 8 is a value for somethign i have unassigned
That is not a bitmask, that is a layer index
you are not bitshifting based on that layer index, you are just passing 0
then why are they both called layers??
One is a layer mask, one is a layer
your mask looks like this:
00000000000000000000000
All bits are 0, ie. there are no active layers in your mask.
you need something likes: (1<<index1)|(1<<index2)
Again, my resource explains this, how to make them, and also has another resource linked at the bottom that goes into them in extreme detail
okay, attempting to call it via a bitshift by pre-claiming it as a var seems to be giving similar results:
[SerializeField] LayerMask layerMask = 0<<3;
[SerializeField] LayerMask layerMask; and set the mask in the inspector
0 << 3 is not doing anything also
bitshifting 0 will produce 0.
0<<3=0b000000....
tbh never heard the concept of bitshifting so all completely new to me
good thing there was a resource explaining bitshifting on the very page I continue to talk about
I wonder if @quartz folio has something that talks about bitshifting? 🤔
i read it, it just seems very vague/verbose so even though i read it, it sorta is just noise on a page to me
you can image that you are puttin a one (or zero) at some positions in 32-bits int
eg 1<<2==0x0000 0004, 0x is hexadecimal form
You're going to have to be more specific, because otherwise it just sounds like you're not paying attention
i'm not trying to ignore that, more just it's talking about stuff in an abstract way that i don't follow well. it's like saying
"an engine is like a stick of tnt in a metal box", abstract enough they make sense, but the page itself fails to connect any dots for me to be more specific
The problem is that an int can’t represent multiple layers. That’s why it needs to be a bit mask. Each bit in the bit mask represents if the layer is on or off. (Eg. 1010 means layer 0 and 2 are on) (that’s why the int “0” wasn’t working, because 0000… means all layers are off)
okay, i can understand that conept, i forget the name but it's basically a bit array
Yup pretty much
0010 = 4 and all that
0100 but yes
i was taught to read it left to right
big endian, little endian, programming is pain
something about left most being the input and the system counts up from their but i digress, my brain is a soup of other peoples knowledge lol
oh, doesnt really matter. theres least and most signifcant notation
fair enough, well i learned whatever i said lol
okey, well, back to the og issue lol, here's now where i'm still sorta just spinning wheels or what have you because despite selecting that specific layer, and making sure the ground is that layer, it seems to be failing to register a hit
lines should be green/cyan if something is hit
ah, got it, simply issue with the ui scan distance being set to 0
well, thanks for everyones help, apprecate it and the education!
when you debug draw ray, always make sure you multiply by the max ray distance (the debug i showed way earlier did this). It gets especially confusing when the visualization is not visualizing properly