#archived-code-general
1 messages · Page 230 of 1
You can use Debug.DrawLine and Debug.DrawRay to visualize raycasts to help debug them.
Glad you solved it 🙂
Thanks for ur help! Legend
I have a problem though. When holding the spacebar, the player is able to still jump in thr air
How could I fix this?
Nvm
i was making a pickup and drop system but when i put the game on, the gun just goes in a random place, locks in, and rotates with the camera, i drop it and pick it back up, then it starts raising while im spinning the camera around, is there something i can show for help?
i need so much help im so confused
private IEnumerator PerformDash()
{
isDashing = true;
dashesRemaining--;
Vector2 dashDirection = new Vector2(Math.Sign(inputHorizontal), Math.Sign(inputVertical)).normalized;
if (dashDirection == Vector2.zero)
{
dashDirection = new Vector2(transform.localScale.x, 0).normalized;
}
Debug.Log(dashDirection.x + " | " + dashDirection.y);
Vector2 targetPosition = (Vector2)transform.position + dashDirection * playerData.DashLength;
float elapsedTime = 0f;
while (elapsedTime < playerData.DashTime)
{
rb.MovePosition(Vector2.Lerp(transform.position, targetPosition, elapsedTime / playerData.DashTime));
elapsedTime += Time.deltaTime;
yield return null;
}
isDashing = false;
}
i wrote this coroutine to dash the player character in one of 8 directions (Left Up Down Right, and 4 in betweens)
it works, except for the fact that after arriving to targetPosition you stay suspended and unable to move for a little while before it ends, and i cant figure out why for the life of me....
even gravity doesnt affect me
Your position lerp is not linear. It would move less and less each frame up to the point where you wouldn't see any movement with a naked eye.
Instead of using transform.position as a first parameter, cache the original position and use that instead.
ohhh that makes sense. Thank you!
Trying to animate my player character running when input is detected and when it stops moving, but it never goes back to ide, here is the code, what am I doing wrong here? I checked the triggers too, they should be spelled correctly
here is the fix
Uhhh I cannot see the screenshot is a little small
Ok thanks for being cryptic, I would like to learn why I messed up
I can see the little mark over the equals sign so I guess I will mess around with that, so thank you, I guess lol
Wait. I'm a bit confused. You're checking if the players distance from origin is less than .01, then you set it to Idle? Is this a game where you stay near origin and it moves you just outwards a little to simulate movement?
Just so we understand better
Honestly it's a student project so I'm trying to set up the animation and stuff. I have not made this movement script so I cannot fully say what it's doing. From my understanding and so there's more context here is this part of the scripts as well
We have the player look towards the mouse position and then all those vector locations the camera is facing then adding them to the players transform when they input times the speed since we have different speed types
That's how I understand it at least. Though I'm sure I'm not seeing the full picture
It's preferred to share the !code, either by posting a small code block or using a website. Screenshots are hard to read (as you've witnessed) and we can't copy/paste into our editor to help debug or fix . . .
📃 Large Code Blocks
Use 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 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 would put a couple Debug.Logs in there to see the value of move
some debug.Assert never hurts
assert statements are like butter. even if it looks sickenning, you can’t have too much
Hey all!
Loup&Snoop oh yeah you're the one I talked to
So I was just testing some stuff in my game
I was using the terraria sprite as a filler, such and such
I am using transform.rotateAround to rotate this butter ball around the player
However when he moves, I use a flip function to flip him
But I don't want the ball's position to flip so I can't child it
When I move the player however, then it causes the ball to move further away from the player and still orbit
How do I maintain this ball's distance from the player without parenting it? I tried using transform constraints and that did not work either
this.transform.RotateAround(player.position, Vector3.forward, 200 * Time.deltaTime);
If you use proper flip, that should only affect the sprite renderer.
What exactly are you doing in your "flip function"?
I'll just drop this here
https://docs.unity3d.com/ScriptReference/SpriteRenderer-flipX.html
Ah
I'm actually flipping it using transform
*= -1
Yeah, that would affect all it's children.
Yeah
Another way is to separate the controller from the visuals. Then you can do whatever you want with the visuals transform, while the orb would be parented to the controller.
That is not usually a good way to do it. Sometimes it has its uses, but it doesn't seem like what you want here
Yes
Thank you :)
Thanks
Howdy, while making a combat system I ran into some funny type stuff that I dont really know how to put into words but basically:
public void someMethod(){
if(itemInstance is MeleeWeapon && (Weapon)itemInstance.AttackTriggered){}
Where Item is the parent of Weapon (which contains the AttackTriggered bool) and Weapon is the parent of MeleeWeapon
I have done something similar before without issue but unsure why I am unable to cast itemInstance as a MeeleWeapon after checking that it is a Weapon
you're trying to cast bool to Weapon ? 🤔
Im trying to case itemInstance as a Weapon to access the bool...
I get what you are pointing out however
Does MeleeWeapon inherit from Weapon?
I'm back
So I have another question
Earlier I was making a ball revolve around the player
if(itemInstance is MeleeWeapon meleeWpn && meleeWpn.AttackTriggered)
My idea is to revolve the ball a lot
And once it reaches a threshold, rotate it towards mouse pointer
And then shoot it
At that angle
My issue is, I've gotten mouse angle and everything
But when I apply:
rb.AddForce(transform.forward * 5000, ForceMode2D.Impulse);
The ball just falls
It doesn't go at the angle I have rotated to
you can most definitely type this all in 1 message..
ah I see, I didnt know you could define something in the same line as type checking... Thats super helpful!
tyty
Sorry
Is it due to the fact that I'm only just setting the rb to kinematic before I launch it?
If my code was to work, it should launch this rb at the angle I've set its rotation to, right? However the ball just drops down.
In the inspector, I can see that the z-angle is being set correctly
It's 2D, you probably want transform.up/right instead of forward
Forward in 2D is the direction the camera is facing
Sorry this does not fix it
Here's a video that shows you the debugging
And what happens, it does not work.
Either do not work, it does something very wacky but according to my code it should only be launching it once?
Thanks however that's helpful to know for the future
Please give me an idea of what scripts and interfaces I would need if I had to create a money management system in the sense that - there are different characters who have certain qualities as well as money, there is a certain service that deals with transferring money from the character to the hero following certain conditions or events. Please guide me in this direction from an architectural standpoint.
im unsure what you mean by "characters who have certain qualities" so I cant answer there. As for the money management system, I would treat this as I would treat a health system. By having a component that holds and manages the characters money, anyone that has money will have this component. i dont really see a reason why you would want interfaces for this
the script that manages money basically needs to store a float and have a way to subtract from itself and give to someone else. Then other scripts would be storing the conditions and events that you describe, all they need to do is have a reference to your money manager script and know who to give it to when the condition is fulfilled
Hello,
Is there a way to update the duration of a "wait for seconds" after it was entered ?
example:
some code >> starts wait for seconds (duration = 3)
some other code >> add 5 for duration to whatever is left to wait for seconds
could this work using a var ? Does the wait for seconds checks how muc his left eac htime
Just WaitUntil then?
this could work but this means that i manually track the time myself ?
Yeah, I would WaitUntil your timer expires. Afaik you can't do what your saying.
ok ty
Can someone please help me with this
I'm still stuck
Not sure where to put this. I am using the Vuplex.Webview plugin to show websites. Unfortunately, the plugin takes the chromium OS language instead of the URL it gets passed in. So if I pass in a german or english website, it always defaults to the english one inside Unity. Anyone in here with experience in that plugin and how to probably ignore the setting or override it? The documentation talks about command line tools, but they do not seem to have any effect.
is there a way to have something like WaitUntil but without frezzing the whole execution ?
Use async tasks or similar for example and use callbacks to setup your logic
There is currently no async support in Visual Scripting so i guess ill do somehting else
Dude can someone help me please
I can not figure it out
And have trialled and errored
For a full day
Ohh, sorry, did not know you are using visual scripting, my bad
No problem
from the video there seems to be something wrong with the whole position calculation. I would comment out line by line and see, what happens when I turn on one thing after the other.
Sure, however
When I do that
It becomes apparent that the issue is with the rigidbody not the angle
Since when I do a rotation test with mouse, it works well.
And did you check the suggestion about transform.forward?
Yes
That's what I did in the video
I showed that it's the same for each transform method
Ah , got it. I will have a look at this later more closely, if its still an issue then. Gotta go, so sorry for the quick jump in and out
Sure thank you
https://docs.unity3d.com/ScriptReference/WaitUntil.html
You should just use it in a coroutine. You already used a coroutine for your WaitForSeconds thing, so I assumed you would just know how to do it, or search the docs.
Oh, if your using #763499475641172029, you should probably ask there.
yeah but i like asking here because most of the time the logic is the same
i didnt though about that
i'll try ty
Heyy, I have a really weird problem when I go to build my project. I have a buoyancy system set up that adds force to a list of transforms based on how far under the water they are. In the unity inspector, it's working fine, but once i build the project it stops working altogether, if anyone had any clues or tips on how I could potentially troubleshoot it further anything is appreciated, im very lost.
This is the code for the system. Its pretty much-written word for word from this tutorial. https://www.youtube.com/watch?v=iasDPyC0QOg
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
[RequireComponent(typeof(Rigidbody))]
public class BuoyancyObject : MonoBehaviour
{
[SerializeField] Transform[] floaters;
[SerializeField] float underWaterDrag = 3f;
[SerializeField] float underWaterAngularDrag = 1f;
[SerializeField] float airDrag = 0f;
[SerializeField] float airAngularDrag = 0.05f;
[SerializeField] float floatingPower = 15f;
[SerializeField] TextMeshProUGUI Text;
[SerializeField] WaterMannager waterManager;
Rigidbody m_Rigidbody;
bool underwater;
int floatersUnderWater;
// Start is called before the first frame update
void Start()
{
m_Rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
private void FixedUpdate()
{
if (m_Rigidbody == null)
{
Text.text = "NOT WORKING HERE";
}
floatersUnderWater = 0;
for(int i = 0; i < floaters.Length; i ++)
{
float difference = floaters[i].position.y - waterManager.WaterHightAtPosition(floaters[i].position);
if (difference < 0)
{
m_Rigidbody.AddForceAtPosition(Vector3.up * floatingPower * Mathf.Abs(difference), floaters[i].position, ForceMode.Force);
floatersUnderWater += 1;
if (!underwater)
{
underwater = true;
SwitchState(true);
}
}
}
if (underwater && floatersUnderWater == 0)
{
underwater = false;
SwitchState(false);
}
}
void SwitchState(bool isUnderwater)
{
if (isUnderwater)
{
m_Rigidbody.drag = underWaterDrag;
m_Rigidbody.angularDrag = underWaterDrag;
}
else
{
m_Rigidbody.drag = airDrag;
m_Rigidbody.angularDrag = airDrag;
}
}
}
Follow me on Twitter : https://twitter.com/ABeginnersDevB1
Support me : https://www.buymeacoffee.com/VincentA
Discord : https://discord.gg/h9RCbRNTXt
This was made using Unity 2020.3 LTS and HDRP 10. Any other version may vary.
Music https://www.youtube.com/watch?v=IV8N-gy5QZg
0:00 Introduction
00:28 Scene Setup
01:11 Shader creation time...
Troubleshoot with Debug.Log or the debugger as normal
As long as it's a dev build log statements will show up in the application log
sorry im still a little new to unity, how do I see the log in builds?
never mind thankyou google XD
Hey so I've got a question related to code architecture. I've got a game where multiple NPCs need to coordinate the completion of one big task. Imagine some Sims-like situation where for dinner to start, there needs to be 4 NPCs at a table. They need to realize it's time for dinner, where to sit at the table, and that they should eat.
I want to be able to tell an individual NPC to leave dinner to go do something else, and I also want to be able to end dinner and "free" all NPCs at any moment. Any suggestions?
The NPCs have a task-based system where I can queue up a bunch of tasks for them to do and they'll work their way through the queue.
It's the group-based tasks that I'm unsure of how to best handle.
the group task just needs a central point of contact to notify a group of NPCs to remove it
or, you could make group tasks erase (or outprioritize) their normal queue of tasks
i assume one NPC can only have one group task at a time, and that one group task takes priority over any other tasks
actually, I would handle group tasks like a separate queue that takes higher priority
each time you check for next task to do: if priority queue has something, then do it. else do from normal queue
then you can ask one specific NPC to dump its priority queue at any time, which automatically returns it to its normal queue of tasks
and an NPC finishing a priority tasks will automatically start the next priority/normal task
then, for group management, group tasks would just need a manager with a collection: List<GroupTask> activeGroupTasks;
each group task has a list of all NPCs that are a part of it.
GroupTask : Task
and give Task a method public virtual void OnTaskDoneBy(NPC npc);
Task: OnTaskDoneBy(NPC npc) {}
does nothing
GroupTask: OnTaskDoneBy(NPC npc) {
participatingNPCs.Remove(noc);}
does this help?
Goal Oriented Planning Action can be a good way to handle most things you might face for this type of AI.
it’s basically a command pattern
but this is the big issue
It is more than a command pattern. (GOAP)
a bit more, but not too tough
Enough to make a difference
the hard part is the command pattern-like part. the easier part is managing priority
The main difference is how it automatically find what available command there is given a state and a goal. It can construct multiple command to get to the end goal.
yeah, i think that is a good idea
Most of the AI would boil down to "here's an explicit list of things to do, go do it". I don't need something nearly as dynamic as the sims.
For now*
lol, well hopefully I don't fall into the scope creep trap 😛
looking into GOAP, i think it is a good tool, but might be a lot bigger than needed here. depends on what he needs
You decide, but I really believe that it is the best time to implement the pattern. Later, you might find yourself with the needs and it would cost you greatly.
Like I will never be in a situation where an AI needs to get "warm" but needs to know to get fire wood, to light a fire to get warm.
In my case NPCs will be explicitly told to do something, and will be given explicit instructions on what to do.
Not really what you said 😛
They need to realize it's time for dinner, where to sit at the table, and that they should eat.
Fair I could see it being interpreted like that.
GOAP is going to be a bit of a rabbit hole if you don’t need it
I was more going for "these are the steps required to do dinner".
as I see it, your main options are to use a priority queue or to use GOAP
Currently I have a priority queue.
to be clear, a priority queue AND a normal queue
so you dequeue from priority queue if there is a high priority task available. Otherwise, you go through normal queue
then tasks can be assigned different priority levels
NPC picks the highest priority queue that has at least one task in it
does that make sense?
Ya it does. Though I'm wondering if I could end up in like... priority hell 😛 where I'm like "ok this task has high priority but this would should always be higher than that."
the alternative is GOAP, which requires you to construct a whole list of actions to reach a specific goal. GOAP will make the NPCs smarter, but also more difficult for player to do exactly what they want.
So I'm wondering if I should just have 1 list that acts like a queue, but also sorts by some defined priority.
i would have an array of queues
iterate through array, and the first queue that has something in it: go do it.
array index corresponds to priority
when a new task is added, check to see if we need to put down current task
one binary heap is enough, you can push tasks with same priority into it
It shouldn't be too complicated to implement a sorted-by-priority queue, assuming tasks can't have dynamic priorities.
heap is faster. but also more complex to implement, i think
if the priority of task is dynamic, it is terrible
the only way to pop is to iterate the whole array and remove as swap back
if you have dynamic priorities, then GOAP is the way to go
priority queue[]/heap is simple for more simple behaviour imo
ah, you can still use sorted set, but it runs slower than heap
delete then insert it bask
i’m assuming total distinct priority levels is a very small number
this can work if you just make a Comparer that compares priority then task age.
Though tbf the priority of tasks is less my issue. It's more the coordination of a group task.
do what I said before then
GroupTask : Task
Task: public virtual void OnDoneBy(NPC npc) {}
GroupTask: public override void OnDoneBy(NPC npc) {
participants.Remove(npc);
if (participants.Count == 0) {
whatToDoWhenDone
}
}
and GroupTask has a list of participants.
make sense?
who is executing that task?
the TaskMaster . . .
every NPC in the participants list has that group task in their queue/heap/whatever
GroupTaskManager can keep a collection of active group tasks. And GroupTask can report back to it when it is complete
So the GroupTask is given a reference to whoever is managing this group task, and tells the manager when it's done?
WhateverMonobehaviour decides what NPCs need to be a part of a given group task. Then it asks GroupTaskManager to assign. GroupTaskManager maintains a list of active group tasks. GroupTask’s constructor assigns the task to all the NPCs. When GroupTask is done, it tells GroupTaskManager it is done, and also tells WhateverMonobehaviour (that constrcuted it) that it is done.
Has anyone been able to get custom rich text tags working well/properly, I know of using links but that method sucks, I found a old forum post about editing the TMP_Text.cs to add my tags but I have the issue of the class being regenerated on the spot after editing it
You probably need an interface: ITaskCompletionReceiver {
OnTaskComplete(Task task);}
This way GroupTasks can specifically hold a reference to the thing that needs to be notified, and tell it that it is done.
so WhateverMonobehaviour : ITaskCompletionReceiver
alright I'll give something like that a try
I dont exactly like a task having reference to the thing that is managing it (which also has a reference to the task), but meh
all tasks should keep a reference to the thing that needs to know when it is complete
dinner table should get notified when a task for setting the dinner table is done
a building should get notified when a wall-building task is done
Task could also store null, to notify nothing when it is done.
no that makes sense
I guess for some reason I thought the building having a reference to the tasks as well would be odd.
For this example.
i mean the task has a reference to the building’s behaviour
probably a list of ITaskCompletionReceivers. So if you need to notify many behaviours when a given task is done, you can do it
Hi guys who know what is the name of the plugin to clone a project to have 2 unity windows ?
ParrelSync?
thx you, because i'm working on a phone game and its too long to build and transfer on a phone ahah
Hello everyone, I want to make fixed time jump without using rigidbody. I'm currently using bezier curves for distance jumps and it works splendid, but I'm having tuble when I want to do a static jump, since the start and end points are exactly the same. Should this approach be working anyway and I've missed something? Or does bezier curves not work with same origin and end point?
In the latter case, does anyone have a solution I can use?
It's unclear how you're applying bezier curves to the implementation of a jump mechanic
Thanks for the reply, but the case was the first! Bezier curves work with the same start and end point, I was just using the wrong time variable. If you are interested on the solution I can share the code:
if (isSmashing)
{
if(currentSmashTime <= smashTime)
{
currentSmashTime += Time.fixedDeltaTime;
Vector3 calculatedPoint = CalculateBezierPoint(currentSmashTime);
skinHolder.transform.position = calculatedPoint;
}
}
This is called on the fixedUpdate.
public Vector3 CalculateBezierPoint(float time)
{
float u = 1 - time;
float tSquared = time * time;
float uSquared = u * u;
Vector3 calculatedPoint = uSquared * startPoint;
calculatedPoint += 2 * u * time * controlPoint;
calculatedPoint += tSquared * targetPoint;
return calculatedPoint;
}
This is the calculate function.
My issue was that this same character has 2 jumps, and the CalculateBezierPoint function, instead of asking for the time as an argument, it was using the time from the first jump, when I was testing the second one. I have this setup because I want the jumps to have a precise jump time, and the 2 jumps have different jumpTimes.
The variables startPoint, controlPoint and targetPoint are computed before the jump starts, on the same function that enables isSmashing.
When handling changing resolution or other graphics settings. Do most games load a default resolution then switch after reading the player prefs, or is there a way to get the application to load directly into the last resolution settings without having to run a script to change it?
I have a scroll view populated by Buttons. It works fine, you can press the buttons but also drag to scroll up/down. The problem is these Buttons also have another component on them that implement the OnDrag events. This makes it so that you can drag on the buttons to scroll. Is there any way to disable the OnDrag events without disabling the component?
what component is it?
It's a script I made to display item information in my game. It implements the OnDrag events so I can drag items between different inventory slots. In this case I don't want to be able to drag the items but I want to keep the component.
What you could do is remove the IDragHandler interface.
In the case when you want it draggable add an EventTrigger component and assign it to your functions.
otherwise leave it off
ah I didn't know about EventTriggers, thank you!
guys, I've been trying to use the the new UIBuilder ListView to create a high scores list. I've created a new Visual Tree asset for the list entry
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
<Style src="project://database/Assets/UI%20Toolkit/UGUI/listEntry.uss?fileID=7433441132597879392&guid=6ba520f1250203b4d948fbbe4b670fa3&type=3#listEntry" />
<ui:VisualElement name="parent" style="flex-grow: 1; flex-direction: row; width: auto; height: auto;">
<ui:Label tabindex="-1" text="Label" parse-escape-sequences="true" display-tooltip-when-elided="true" name="name" class="nameLabel" style="width: 30%; margin-top: 4px; margin-right: 0; margin-bottom: 4px; margin-left: 2px;" />
<ui:Label tabindex="-1" text="Label" parse-escape-sequences="true" display-tooltip-when-elided="true" name="score" class="scoreLabel" style="flex-shrink: 1; flex-grow: 1; width: 70%; margin-top: 4px; margin-right: 2px; margin-bottom: 4px; margin-left: 0;" />
</ui:VisualElement>
</ui:UXML>
and I created a list to be the info for the ListView. But I son't know how to correctly do the binding, for the labels on the ListEntry visual tree asset to change according to the list content. Any Ideas how can I make that happen?
god this gives me flashbacks to xaml
damn, it's down there in artists tools, and it's almost all code
thank you, I'll move the topic there
holy shit that language looks like pain
ive been following this tutorial on a tomb of the mask clone
https://youtu.be/oElwJa6SkVU?si=4tgypnLpxkBpl3Ff&t=88
its at the time stamp but they go into photoshop and after all new code randomly appears and im having trouble working it out.
Id appreicate any help i can get to complete this code
this is what i have so far:
Music:
NIVIRO - Memes [NCS Release]
there is no need to crosspost this everywhere mate
how many channels do you think you have to post in?
i bet its not the most important problem that requires to post this many times
im on a deadline sorry
not our problem , follow the #📖┃code-of-conduct
So take them all out and do it properly this time !code
📃 Large Code Blocks
Use 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 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.
wha?
remove all your posts and post 1 in the correct channel and do it properly
or the mods will do it for you. and you really don’t want the mods to do it for you
couldve just said that
idk what you meant by this
Guys, why is my model not using the run animation?
looks like you've got a NullReferenceException to fix. Line 48 of InputManager.cs
you can try taking some screenshots of the code on the screen, uploading it to chatgpt gpt4, and then ask it to transcribe the code for you
https://paste.ofcode.org/AvYAAPMR3WcUpRnHGsWRsm
So what do i need to do?
fix your NRE
identify what is null on that line.
identify why it's null at that time.
fix it
as with all NREs
anyone any idea why the Debug in input name outputs the variable corectly but the debug in Continue says Null after that?
putting the things from continue into Input name makes it work but i wnat so save multiple things so this isnt an option
impossible to say since it's unclear when and where either of these functions are running
Could be on completely different instances of the script for example
so i input a text into a TMP input field, press enter, it shows me the correct variable, then i press the continue butteon directly underneath it wich callls Continue
You would have to show how all that stuff is set up
Any other scripts, the buttons, the input field, etc
Looks like you have two completely separate instances of the CreateCharacter script
Which falls in line with what I mentioned above
Im trying to create a gun sway. But my pistol ends up looking down when pressing play. How am i able to change this so the pistol is aiming forward
public class GunSway : MonoBehaviour
{
public float smooth;//float that holds the sway smoothness amount
public float swayMultiplier;//increases/decreases the amount of sway on the gun
private void Update()
{
//get the mouse inputs for both x and y
float mouseX = Input.GetAxisRaw("Mouse X") * swayMultiplier;
float mouseY = Input.GetAxisRaw("Mouse Y") * swayMultiplier;
//calculate the target rotation
Quaternion xRotation = Quaternion.AngleAxis(-mouseY, Vector3.right);//Calculates target rotation on x axis, -mouseY because inverted otherwise
Quaternion yRotation = Quaternion.AngleAxis(mouseX, Vector3.up);
Quaternion targetRotation = xRotation * yRotation;//combine both x and y rotation
//rotate the gun
transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, smooth * Time.deltaTime);
}
}
First thing's first - make sure your 3D model was imported correctly into Unity. With tool handle rotation set to "local", double check that the blue arrow on the move tool is pointing out from the barrel of the gun model appropriately.
The blue arrow is not pointing out the barrel
i have to always set the gun x rotation to -90 since its not pointing forward
so how can i use the -90 rotation intstead of transofmr.local rotation
@leaden ice
by far the simplest and best way to fix this is to re-export your gun model from Blender or elsewhere with the appropriate settings / orientation
how should i import it with correct settings
Exporting from Blender to Unity can result in rotation and scale issues that are not intuitive to fix. This video teaches how to fix them for meshes attached to an armature.
Complete Playlist:
https://www.youtube.com/playlist?list=PLq7npTWbkgVBAtQs4p4iYxlfWrKRkNc6O
Relevant links:
Penguin Mesh Download - https://immersivelimit.page.link/pengui...
Could someone help me with this log when i try to use google firebase?
that thing is a shite show
your error seems to be related to you missing something IOS
probably XCode
the error , read it
usally says
are you on a macOS device?
No
did you set your target to iOS?
just delete the IOS dll then
That's the weird fact
@tranquil canopy how did you install the firebase package?
did you copy and paste something from somewhere?
was the thing you copied and pasted, a bunch of folders in windows into your Assets/ directory?
i thougt it but i didn't do it cause i thought i could break something
yep
is that what the docs say to do?
i followed them carefully
Its been a long time I think I had to do something like that
So i just opened my project i'v worked on for weeks. 2 days off and now this sht happends. Everything is deleted and terrain is completly destroyed,.
What is this sht??????????????
lookup that error in google they have a github post on it @tranquil canopy
i guess follow them again. https://firebase.google.com/docs/unity/setup
not sure I see code question here, do you not have a Commit you can revert to ?
i'll try it... it could be like that... the video i've also seen did it with IOS too... could be that
Where should i post it then? im now here
https://github.com/googlesamples/unity-jar-resolver/issues/622 issue @tranquil canopy
Thanks for bringing this to our attention. This issue could be solved by making sure you have the iOS build support in your Unity version.
try that
did already
okk
Hi, having an issue with my camera - it resets/turns around just once. Code looks fine (no resets after time, etc..).
Since I'm having Camera as a child of Player object (with CharacterController) I feel like it may be connected to Logic/Physics frame sync, ...
I checked profiler and saw one spike exactly when the camera glitch happened. In that very spike there is no PhysicsFixedUpdate - is that correct?
Any ideas?
without seeing the code it's hard to say
Can I share the code here or better to upload it somewhere?
📃 Large Code Blocks
Use 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 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.
PS: I tried to move Movement to FixedUpdate and View to LateUpdate, didn't help => leads to horrible tearing of object edges which player is strafing around
Is m_inputView tied to mouse delta input?
yep, by the "new" Unity Input System
Brackeys special
If so you are improperly multiplying Time.deltaTime into mouse input. Mouse input is already framerate independent.
Remove Time.deltaTime from the mouse rotation calculation
(and adjust your view sensitivity down to compensate)
trying...
LEGEND!
Although - it still "freezes" a bit.
Before it froze and rotated the camera. Now it only freezes in that "spike".
well that's just a framerate hitch full stop
And thank you very much for very quick and valid explanation of the delta. I didn't realize that at all
weird, nothing in the scene almost, my pc is highend (4090, etc..)
learning profiler.. so not sure what to look at
It goes from 2ms to 6.5ms on EditorLoop - nothing else. Is that too much? 6.5 ms should be nothing, right?
Oh, I found this: Physics Queries: 265 hmm...
that is indeed very little, 60 fps will be around 16.6ms per frame. You dont really need to worry about the editor loop because it wont exist in a build, although you can swap your profiler to edit mode to see what the issue really is. For me i had to swap on incremental gc once and that was about the only thing i had problems with in editor loop
thanks @lean sail - I think that's alright, I didn't know there is other profiling information below the one I posted - basically I was looking at CPU only but the spike is actually in PHYSICS category
well it's not nothing. It's about 1/3rd of your frame budget for 60FPS, and basically the whole frame budget for 144FPS
but it's editor only
hm, so you think that physics queries are alright to be 265? - I'm going to make a build and try
there should be a button that says Play mode which you swap to Edit mode? i think on the profiler. I dont have unity open but should be about accurate
Then you'll want to look at the hierarchy instead of just the graph alone, use the graph to identify spikes then click on the graph so the hierarchy can focus in on what is causing the spike
Sharing my whole class for the PlayerController https://paste.ofcode.org/rj6pFtCrSPaZp4WCQuxdkK
gonna try
I don't know, can't see anything special.. I mean I probably see the spike, but there is just standard stuff in the editor
Yeah, it's the only thing that consumes the most of it..
I have one idea
well I had 2 custom Editor scripts that had been using the OnGui - I compeltely removed, it didn't help :/
OnGUI can also refer to Canvases as well, you can try turning on "Deep Profile" and "Call Stacks" so you can see what functions might be causing GC.Collect for you
Can someone explain to me why the same operation produces two different results here ?
I'm beyond baffled
I tried to turn of HUD (having only 1 canvas, so easy test) - same resut, but thanks for the tip! Going to try the deep profile
+= when you add the height to a
-= when you add the height to b
why is the result of the addition positive x but the result of the subtraction not negative x ?
(If you want the upper sphere to be above the collider you should add the radius, not subtract it)
why is the bottom sphere not within the collider?
the distance from the center should be the same value.
when deep profiling on it runs like 30 FPS and doesn't create the spike :/
you are subtracting the height and then the radius
if you want it at the bottom of the capsule (and inside), then just subtract the height and add the radius of the sphere
I just saw it, oh man I'm so stupid
🫂 🫂 🫂 🫂 basic Math where have you been all my life
deep profiler does take more resources but im unsure about your issue, can you check if you have incremental GC turned on
thanks guys
it was off
turning it on should just solve this then
wow, it really sovled the issue
#archived-code-general message
i probably shouldve just suggested it more clearly here
Thank you very much! I had no idea there is such an option and no idea why it was off (reading the documentation - it says it should be on by default).
I saw that as well, no idea why mine was off either
thanks a lot, spend hours on that, but I'm super happy for all the help @lean sail and @soft shard and @leaden ice - you tought me a lot today!
Hey, has someone ever used google firebase? i have 2 logs and i dont know how to solve them...
Hello. I've noticed something weird while making my game. Everytime I press play, instead of showing the right tiles (image 1), the tiles are shown in random order (image 2). Is has something to do with the terrain sprites and the order that I put/copy-pasted them?
You'd have to explain what we're looking at
the map of the game
I hope this video explains well the situation
Which is what? A tilemap? How is it populated?
@heady iris I fixed my pausing bug from yesterday. My solution was to make better use of a class I made to allow me to run methods in EarlyFixedUpdate. It's just a singleton that invokes a delegate every fixed update, with super high execution order. Also LateFixedUpdate, to get things in immediately after collision callbacks are done.
Looks like you have some code doing world/chunk streaming. That code is populating the tilemap
That's the code responsible
can I give you the code and see what's wrong there?
Well you can post it here. But I assume it's just because whatever is in the tilemap in the editor doesn't matter because you're streaming the data either from a noise function or some saved data
!code
📃 Large Code Blocks
Use 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 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://gdl.space/onunijuxic.cs @leaden ice
Yep like I said, the script is placing tiles based on this terrainTiles array
Whatever you have set up in the editor will be ignored/overwritten
if (Quaternion.Angle(transform.rotation, _targetRotation) < rotationThreshold)
{
// Apply the movement only when the rotation is within the threshold
transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime);
}```
I have this code here and I am stumped as to why the player is moving at different speeds on my computer vs my partners
perhaps share the rest of the code
private Vector3 CalculateMovementDirection()
{
// Calculate the movement direction based on arrow keys or WASD
Vector3 moveDirection = Vector3.zero;
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
moveDirection += Vector3.forward;
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
moveDirection += Vector3.right;
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
moveDirection += Vector3.back;
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
moveDirection += Vector3.left;
// Normalize the movement direction if it's not zero
if (moveDirection != Vector3.zero)
{
moveDirection.Normalize();
}
return moveDirection;
}
TThis calculates the movement direction
Can you show the full script
if (_normalMovement)
{
// Set movement speed based on input
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
currentSpeed = sprintSpeed;
}
else if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
currentSpeed = walkSpeed;
}
else
{
currentSpeed = jogSpeed;
}
// Move the player
NormalMovement(CalculateMovementDirection());
}
``` and this is what gets called in Update
{
// Translate the player's position based on the movement direction and amount
//Vector3 newPosition = transform.position + movementDirection * currentSpeed * Time.deltaTime; //! Change to fixeddeltatime if using fixedupdate
//transform.position = new Vector3(newPosition.x, transform.position.y, newPosition.z);
// playerRb.MovePosition(newPosition);
// Rotate the player to face the movement direction
if (movementDirection != Vector3.zero)
{
// Calculate the rotation based on movement direction
_targetRotation = Quaternion.LookRotation(movementDirection);
// Check if the rotation is close enough to the target rotation
if (Quaternion.Angle(transform.rotation, _targetRotation) < rotationThreshold)
{
// Apply the movement only when the rotation is within the threshold
transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime);
}
// Interpolate the rotation
transform.rotation = Quaternion.Lerp(transform.rotation, _targetRotation, _rotationSpeed * Time.deltaTime);
// Play correct animation
if (currentSpeed == sprintSpeed)
{
this.GetComponent<PlayerAnimationHandler>().Player_Ani_Sprinting();
}
else if (currentSpeed == walkSpeed)
{
this.GetComponent<PlayerAnimationHandler>().Player_Ani_Walking();
}
else
{
this.GetComponent<PlayerAnimationHandler>().Player_Ani_Jogging();
}
}
// if not moving, play idle animation
else
{
this.GetComponent<PlayerAnimationHandler>().Player_Ani_Idle();
}
}```
And this is the NormalMovement() function
Just posting the full script in a paste site !code would be much more helpful
📃 Large Code Blocks
Use 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 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.
Can't share the full script unfortunately
Well transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime); on its own is fine assuming currentSpeed is the same
transform.rotation = Quaternion.Lerp(transform.rotation, _targetRotation, _rotationSpeed * Time.deltaTime); isn't quite a proper Lerp but it shouldn't matter all that much
whats wrong with this?
So given what you've shared I can't say what the issue is
In short, the third variable is not a speed. It's not any kind of rate. It's a percent between the first two.
Multiplying it by deltaTime makes that value go up and down and look shaky. You never want to multiply it by deltaTime
You know how interest is worth more if you compound it more frequently? It’s a similar situation
You wind up with behavior that varies with your framerate
was this authored by chatgpt?
is there a way to make a machine const editable in unity editor? like how Physics2D works?
what is this? why is it rotating, and then moving and rotating at the same time?
Lol no
It’s to make the movement when changing directions feel more realistic and less flipping on a dime
And yes I did it myself
Causes a smoothing effect as you’re changing directions and moving
The player
The player gets rotated at some speed and once it’s within the threshold to the desired rotation it allows the player to start moving
The game is top down 3D
so, quaternions are weird
is the idea that right arrow always moves the player in positive x in the xz ground plane?
or does it move the character "right" relative to where it is facing, like driving a car?
the best way to deal with quaternions is to try to avoid any sort of addition/subtraction or direct modification of ijkl individually
you want to use methods to multiply them, or rotate by
going back to your problem, _rotation speed has units of degrees/sec, and deltaTime has units of seconds. So you are using Quaternion.Lerp with the last number having units of degrees
which is incorrect
the last argument of a lerp/slerp needs to be dimensionless
it seems weird to me, but is your goal that if my character is facing positive z (aka "screen up"), and i hit Right Arrow, it remains stationary and rotates towards ALMOST positive x, and then when it's within a certain threshold, start moving, and continue to rotate towards positive x?
is that really the desired behavior?
lerp/slerp's last argument brings you to a spot between the start and end (0-1) by the 3rd argument
@rich leaf also, when sharing your project, are you using git?
i will tell you now, based on the code you shared, the simplest explanation for why the speeds are substantially different is that you guys do not comprehend what you are looking at. like probably you didn't save and commit your scene, which has a different sprint and walk speed than what is committed into git
because there is nothing wrong with transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime); which is the only place where your character moves in this code snippet
so everything else is a red herring
@rich leaf does that make sense? ignore this quaternion story nonsense, it isn't causing the thing you are describing, although it is indeed glitchy
Game is top down, W corresponds to going up the screen (game is in xz plane), D corresponds to going to the right, etc...
The whole point of the rotation is that lets say I am going upwards (W) and want to change directions to the right by holding D, the players transform gets rotated and then the player is moved forward. However there is a threshold that has to be satisfied in the rotation (ie has to be 90% done the rotation) before it starts moving the player.
The idea for it (and works very well) is to smooth the rotation and prevent the players transform from just flip flopping to face the direction, which works for 2D but looks janky in 3D. You can balance the rotation thresholds to find a good middle ground between responsiveness and looking good
And for this, we use git and everything was up to date. My partner literally copy pasted the player prefab from my current scene i was working on into their new scene and noticed the discrepency
Also, the speeds are set in the script themselves and are not modified in the inspector
I am confused
this code loads a texture from a byte[] array, and falls back on creating a solid color texture if the byte[] is invalid
private Texture2D GetTextureFromBitstream(byte[]? bitstream, UnityEngine.Color backgroundColorForInvalid, UnityEngine.Color key)
{
if (bitstream == null || bitstream.Length == 0)
{
backgroundColorForInvalid = UnityEngine.Color.red;
var solidTexture = new Texture2D(3, 3, TextureFormat.RGBA32, false);
solidTexture.SetPixels(new[] { backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid });
return solidTexture;
}
var imageTexture = new Texture2D(1, 1);
imageTexture.LoadImage(bitstream);
imageTexture.alphaIsTransparency = true;
UnityEngine.Color[] colorData = imageTexture.GetPixels();
for (var i = 0; i < colorData.Length; i++)
{
if (colorData[i] == key)
colorData[i] = default;
}
imageTexture.SetPixelData(colorData, 0);
return imageTexture;
}
In the case where the byte[] is valid and I get the image, everything's fine
For a smooth rotation, consider replacing your Lerp with MoveTowards. Simpler to conceptualize for some people and in practice does the same thing sorta
but in the case where it falls back to the solid color, I get a translucent gray texture in my UI
And I'm unsure why
will look into it thanks
Because look at the code, it should be solid red
And it is if I use EncodeToPNG on it and save it to disk
What effects do i expect to see "incorrectly" using lerp? Everything looks smooth on my end
It's not a linear interpolation and it will not actually reach the desired target.
Are you sure it goes into that if block? Maybe add some logs? Also, you know you can use the debugger to step through the code and see exactly what's going on?
ABSOLUTELY sure
and I'm well aware of the debugger, thank you
I wouldn't really be asking for help if I hadn't exhausted all other options
Okay, then what do you see in the debugger when the issue occurs?
Might also be a matter of applying the changes to the texture.
Like I said. If I use the debugger to call EncodeToPNG on the texture in the if block, I get a 3x3 red texture like I should
proof incoming
that is the texture
But it shows as the gray texture even in the Unity inspector
Not sure what you mean by "use the debugger to call EncodeToPNG", but okay. What about the applying changes part?
you can simply remove the rotation and see for yourself that the issue remains.* set the transform.forward to move direction immediately.
so something else is wrong
Explained here: https://unity.huh.how/lerp/wrong-lerp
You need to call imageTexture.Apply() after SetPixelData
Looks like dlich pointed that out too
focus on what i am saying
comment out this rotation and don't worry about it since it's not essential
Rider lets you run C# code within the debugger
there's an interactive console
waiwaiwait
that might just kill two bugs
Ah, you're using that? There's that feature in VS to, but I'm not sure how reliable it is.
Regardless, my question still stands.
I'm going to put my chips on one of you having a faulty keyboard such that the input isn't being read every frame
lol
i mean he won't share the whole code file
just have to play along with the guessing game, hopefully we hear what the issue was when they find it
ohhhkay so
calling Apply fixed solid textures
but now image textures are broken
the background where the two windows are, well
that should be Windows XP Bliss
now it's just a weird pattern
private Texture2D GetTextureFromBitstream(byte[]? bitstream, UnityEngine.Color backgroundColorForInvalid, UnityEngine.Color key)
{
if (bitstream == null || bitstream.Length == 0)
{
var solidTexture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
solidTexture.SetPixels(new[] { backgroundColorForInvalid });
solidTexture.Apply();
return solidTexture;
}
var imageTexture = new Texture2D(1, 1);
imageTexture.LoadImage(bitstream);
UnityEngine.Color[] colorData = imageTexture.GetPixels();
for (var i = 0; i < colorData.Length; i++)
{
if (colorData[i] == key)
colorData[i] = default;
}
imageTexture.SetPixelData(colorData, 0);
imageTexture.Apply();
return imageTexture;
}
so, everything in the if statement is fine
everything after it isn't
Any idea what could be corrupting it?
Narrowed it down
UnityEngine.Color[] colorData = imageTexture.GetPixels();
for (var i = 0; i < colorData.Length; i++)
{
if (colorData[i] == key)
colorData[i] = default;
}
imageTexture.SetPixelData(colorData, 0);
imageTexture.Apply();
comment this code out and the texture loads fine, no corruption
but I need this code to do what it's written to do
SetPixels instead of SetPixelData
that fixed it
Hello, I need help with trying to add controller support for Prometeo Car Controller?
Working on a project with a group and we trying to do controller support for the car
Literally sent the whole code dude
Huh?
And no it’s pretty obvious by the animations that this isn’t happening
I'd probably verify that with a debug log that shows both the frame number and the movement values rather than eyeballing the animations tbh
I think they're talking to someone way above and just didn't do the reply button
Oh
I'm getting DOTween errors when trying to delete a game object as part of the sequence on the tween. No worries, I can use OnComplete and it works fine. However, Demigiant's OnComplete replaces any other callback if one is set, and I need the OnComplete for other things (sequence queue).
Any ideas?
Have the OnComplete destroy the object and do the other thing too?
E.g. start a new sequence
hm.. not sure I can easily. I have a sequence manager that's .. asking the components for a sequence, and then tacking it's own callback onto the sequence so it can fire the next.
Example, the "reward manager" can ask the "reward renderer" for a single sequence of grant 100 coins, and then stick them in a queue with a callback to fire the next one.. result:
but the .. i can only use oncomplete..
or maybe i could .. append a normal callback instead of using oncomplete
Can the sequence just do something silly like set a flag to destroy the object later or start a coroutine that does the same?
Also not sure I understand what the error is with putting Destroy in the sequence? What kind of error is it?
I'm trying to get the error actually but DOTween seems to be soaking it somewhere.. I think it might be a problem with trying to destroy the object in the same frame as another part of the sequence is finishing? ie, if I tween scale from 0 to 0.5 sec and immediately append a callback to destroy, it .. just doesn't destroy the object. I'll show, one sec
OK, I've figured it out. And.. it's dumb. 🤦♂️
I overrode Destroy(UnityObject) to throw an exception when I tried to destroy a component on a gameobject (accidentally) instead of destroying the game object.
When I (finally) managed to get dotween's logging to show the underlying error, I found it.
The code I posted above even has it correct - it was only when I tried to Destroy(tile) instead of Destroy(tile.gameObject) did it fail.
ah
(tile is some sort of object of mine)
Hi, I followed an advice I was given(because my terrain was disappearing), I rewrote the entire generation script so that it uses multiple connected closed sprite shapes instead of a single shape w many points because I was getting a warning message of max vertex limit being reached(which does appear to be solved now).
However, this new approach results in the terrain being very "unsmooth" and colliders are not nice because there are multiple instead of a single connected one.
I don't know what I am supposed to do in order to achieve a smooth appearance and nice feeling colliders(required for gameplay).
Here's the code
I'll provide an image showing what I mean by "unsmooth" terrain and colliders aswell.
This image shows a small gap between 2 sprite shapes even tho they are right next to each other, what am I supposed to do?
works lovely now.. animations need some love but the whole sequencing and orchestration of it is functional
A bit of unsolicited advice - maybe have this sequencer insert a small (configurable) delay in between each thing too
Yeah.. I think I'd make that part of the component that I'm asking for the sequence from.. like, "how long is your attention required".. and at the parent, instead of queue and dequeue only when the sequence is finished, I'd insert the next sequence after the first one has indicated "that's good enough".
ie: Sequence one takes 5 seconds but 3 seconds is good enough
Sequence two is 5 seconds but 3 seconds is also good enough
Orchestration: Start sequence 1 at 0.0 sec and 2 at 3.0 sec, and restore navigation after 6.0 sec
the animations themselves aren't great but I just needed something to ensure that I could.. queue up 6 animations at once and have them unspool nicely
Alright so going back to my p[roblem from earlier with the player speed being different on different hardware. When the players rigid body is removed, our movement speed is the same. However, the rigid body literally does not get called anywehre in the entire project solution (confirmed by searching through whole solution in VS). We've even commented out everything that had to do with playerRb in the code, but only when the component itself was removed did the movement match...
are there any settings in here that would be framerate dependend even if no scripts call the rigidbody?
interpolate
try disabling that
I am honestly not sure
I just had several instances of rb interpolation messing up the movement
I mean I have an idea of why it's happening but not sure if it's accurate
turning on isKinematic and disabling Interpolate fixed it too
And the weird part is this only seems to change things on their end... mine is unaffected
afaik, interpolate mimics the smooth movement of an rb(movement between fixed updates) by interpolating between the position before previous and previous position
and therefore, when combined with a transform based movement, it completely messes up everything
I am not sure if what I just said makes sense or is true
The constraints are weird to have when kinematic btw
But generally a kinematic body should be well behaved with direct transform motion
Although interpolation is completely unnecessary if you're moving it in Update via the transform
What constraints are weird?
probably
And the y position
it seems to be the interpolation. What is this used for?
might be wrong but a basic idea
and how can you make it consistent across devices if you do want to interpolate?
you don't need interpolation if you are moving the object in Update()
is interpolation used for physics based movement?
it is used to smooth out the movement done in FixedUpdate() which happens less often than Update()
bump
Interpolation is for when the object is moving in the fixed time step of the physics sim and needs to be smoothed out to the display framerate
If you're already moving in Update it's already in sync with the display framerate
Oops sorry I'm slow
Hey I'm unable to understand number of commands in SpherecastCommand.ScheduleBatch(), how should I decide what number to put for "minCommandsPerJob" argument? Does it have to be amount of CPU cores?
Probably trial, error, and profiling
Alright
seems to be even more vague because we don't know how many cores will the end user have 
Start from the total count and look at how long the job takes to perform. If it's too long, divide by 2.
Well, here's a video and he says for 50 sphere casts and value of 10 it's going to result in 5 jobs, one for each core and one core left idle 
can someone help me with my code? i'm trying to make it so the gameobject can be rotated when swiping across screen (like previewing a 3d model) and it works but when moving too fast it starts jerking back and forth
public class DragRotator : MonoBehaviour
{
public float sensitivity = 1;
public float speed = 0.5f;
private Quaternion targetQuat;
private void Start()
{
targetQuat = transform.rotation;
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetMouseButton(0))
{
float pitch = Input.GetAxis("Mouse Y") * sensitivity;
float yaw = -Input.GetAxis("Mouse X") * sensitivity;
Quaternion yawRotation = Quaternion.AngleAxis(yaw, Camera.main.transform.up);
Quaternion pitchRotation = Quaternion.AngleAxis(pitch, Camera.main.transform.right);
targetQuat = yawRotation * pitchRotation * targetQuat;
}
transform.rotation = Quaternion.Lerp(transform.rotation, targetQuat, speed * Time.deltaTime);
}
}
Shouldn't that happen in Update() method? Object being rotated is something that user can see, should see a change each frame 
You don't have to worry about the number of cores. They might not even be available at a time or busy with other jobs.
i was getting same problem when using update() though
Okay
thanks for your help by the way!
You are multiplying the t parameter of lerp by deltaTime, which is wrong
Try just doing MoveTowards or look up the right way to use lerp
bump
Where do you generate the collider?
it is auto generated by shapes
What settings do you have on the sprite shape component?
didnt know about that, thank you!
Try setting the offset to 0
you are a lifesaver :/
it completely fixed the collider it seems, the visuals are not there but I can live w that
is this a multiplayer game? i think you are misinterpreting a lot of different things that are going on
im trying to make a moving platform, but the player keeps changing its scale with the floor and bugs it out, is there a way to keep it from affecting the scale?
Because you setparent so child global scale will be affected
I remember there is an overload of setparent persevere global transformation
so what would be a different way to set the parent without affecting the scale?
whats the overload version 💀 im very new to this lol
Keep the child position rotation and scale in world space while setparent
An overload is the same method, but with a different signature (the parameters you pass in).
public void SetParent(Transform parent, bool worldPositionStays);
This is the other overload. Make worldPositionStays true I guess.
"If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before."
where do i put the public void though? Do I just put it somewhere in the private class or inside the oncollision enter like i tried (and failed)
public void should not be in there at all
It is called method
Jesus guys, I'm sorry for the stupid question but I'm having a brain fart. How do we move an object backwards, regardless of rotation?
collision.gameObject.transform.SetParent(transform, true);
It's EXACTLY what you had before, but with a comma true at the end
💀 oh
as i said
im very dumb and new to this
lmao
You're fine. We all start the path somewhere
What does backwards mean, if it doesn't have to do with rotation?
What it looks like. If the object is facing south, I want it to move north, if it's facing East, move west, etc
Transform.forward
Exactly. The inverse of that
So depending on which way it is... rotated, you want it to move backwards
-transform.forward
I'm having a bit of issues with localmoveZ -1
its still broken nvm
It's supposed to move one unity back regardless, but it keeps moving backwards. Perhaps it's because it has no parent
You have errors. Resolve those first
That seems like a separate issue. Maybe just show code at this point
📃 Large Code Blocks
Use 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 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.
Actually, just to make sure, is this your current code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StickyPlatforms : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Marble")
{
collision.gameObject.transform.SetParent(transform, true);
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.name == "Marble")
{
collision.gameObject.transform.SetParent(null, true);
}
}
}
oh 💀 i forgot to add the ,true to collision.gameObject.transform.SetParent(null, true)
The issue happens when it FIRST touches, so I don't think that is gonna resolve it, but it's a good idea to have it anyway
oh lol
also ik how to fix error #2 but im having trouble with error #1 bc idk how to read errors and i cant figure out if its a problem in the code, or one of the things on the side
Well, the issue is with PlayerMovement on line 35 inside Start. That's all I know from your video earlier
You are trying to access something that is Null
i checked line 35
and its just smth for the scoreText
is it bc the thingy is empty?
Well, as you see from the previous screenshot, you don't have a reference to scoreText
yes
oh alr
there is a distinct lack of syntax highlighting for unity types. make sure that your !IDE is configured 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
does this look better?
yep, looks configured now
fixed all errors but its still acting funny 💀
also now respawning is bugged 💀
this is the whole code for player movement in case u need it ig
!code
📃 Large Code Blocks
Use 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 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.
hello i wanna know how to change the animations from the third person starter assest ?
Is that code related?
I have a question: Is setting a float variable value = 0f the same as set in to float.MinValue
Debug.Log(float.MinValue) and find out
float can be negative
Google it
you can see the value in your ide
Better yet, just make a plain c# project to test this stuff on the side
That too, constants are shown when you hover over them
GetComponentInChildren does this get the component from deactivated objects?
no
Actually GetComponent(s)InChildren has an option to include inactive objects as well
ArgumentException: Illegal characters in path.
System.IO.Path.GetExtension (System.String path) (at <1c8569827291471e9db0dcd976e97952>:0)
ReferenceChecker.Editor.LinkedAssedChecker.CheckPackedAssets (UnityEditor.Build.Reporting.PackedAssets[] packedAssets, System.String& message) (at Assets/_Scripts/ReferencesChecker/Editor/LinkedAssedChecker.cs:41)
ReferenceChecker.Editor.LinkedAssedChecker.OnPostprocessBuild (UnityEditor.Build.Reporting.BuildReport report) (at Assets/_Scripts/ReferencesChecker/Editor/LinkedAssedChecker.cs:21)
UnityEditor.Build.BuildPipelineInterfaces+<>c__DisplayClass18_0.<OnBuildPostProcess>b__1 (UnityEditor.Build.IPostprocessBuildWithReport bpp) (at <8117508d098d40e7b6cab2e14abb2fdc>:0)
UnityEditor.Build.BuildPipelineInterfaces.InvokeCallbackInterfacesPair[T1,T2] (System.Collections.Generic.List`1[T] oneInterfaces, System.Action`1[T] invocationOne, System.Collections.Generic.List`1[T] twoInterfaces, System.Action`1[T] invocationTwo, System.Boolean exitOnFailure) (at <8117508d098d40e7b6cab2e14abb2fdc>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
getting this error when building
where i could find the illegal character?
In your project path
What about inside the project
this is my rotation function
but the issue is that sometimes it rotates endlessly
i heard its because i need to use quaternion rotation
No, it's because you read Euler angles from transform
You need a separate variable to keep track of the current rotation
currentRotation = Vector3.Lerp(currentRotation, ...
transform.localEulerAngles = currentRotation;
also unrelated but incorrect use of Lerp
you are comparing 2 vectors which is almost always not true because of rounding.
it's not incorrect use, just different. In this case it is the wrong approach though.
whats the right approach on lerp in this case?
Lerp(startPosition, endPosition, timer)
when timer is 0 the object will be at startPosition, when it is at 1 or higher it will be at endPosition. At 0.5 it will be in between both values.
Hey All!
I have an issue
Where I have a boomerang that constantly rotates, which causes my transform.position addition with transform.right to not go in a straight line.
I would like the sprite to go in a straight line, while rotating.
Make the SpriteRenderer a child object and only rotate the child. Move the parent as normal
Oh 🤦♂️ I didn't think of that, I really need to start thinking about the power of using children and parents.
Thank you so much
Hi all, would anyone be able to help with CharacterMovement vs deltaTime vs fixedDeltaTime + Update/FixedUpdate/LateUpdate --> in other words, **the issue is: ** My character jumps higher when game is maximized (with more FPS).
I have this script, that covers all the movement, mosue look and jump with gravity. https://pastebin.com/GWk7JDcG
I'm trying all the things like spliting logic into Update, performing Movement in FixedUpdate. Using fixedDeltaTime instead of deltaTime. But nothing seems to fix my issue.
put all physics stuff into FixedUpdate. Also deltaTime and fixedDeltaTime is the same value in FixedUpdate() so it doesn't really matter.
newMovementSpeed.y += m_playerGravity; you forgot DeltaTime here
And you added it here which doesn't make sense:
newMovementSpeed += m_jumpingForce * Time.deltaTime;
Also why are you adding jump force every frame?
That should only happen once, right when you jump
Also you should just save all the DeltaTime stuff till the end, right before the Move call. Right now you have it confusingly mixed in all over the place
I was following some tutorial since I was unable to make Camera as child object of a Player in FPS. The objects in scene where always flickering, etc.. so trying to understand now how it all works. I have done tons of 2D movement/cameras, learning the 3D these days for the first time.
Thanks both for your advices, going to check on that and try it.
Also appreciate pointing out the best practices on where to use the deltaTimes. Thank you!
has anyone ever seen this type of behaviour?
never seen meshes do this kind of blinking thing
all my code that affects the character is disabled
the only thing i do, is spawn the character in which worked with no problem before i imported this character
there cant be a script inside the fbx model already can there?
seems like it was due to an animation it was uploaded with
removed the animation it had and now it no longer flickers
I applied the changes and I think I alrady had it this way. Unfortunatelly now the object edges are flickering :/
Hello, I'm making a puzzle game that has daily levels. I have daily levels made for around 2 years but how would I best cycle through them? I was thinking of using the date together with the daily levels being in resources (they're json files) and then either having them all on a list, using Resource.Load or learning about Addressable.
My question is what would be the most efficient solution as I'll have 8 daily levels per day so I have a lot of files to work with.
In the past I've seen similar issues when someone added some sort of culling that was triggered by transparent objects.
In your case it's most likely badly implemented animation. Try putting the object on empty scene and see if it still flickers. If it's the case, I would suggest opening the animation in some sort of animation editing program and checking if everything is correct (e.g. scale is not set to 0 in some frames).
i just removed the animation entirely inside blender
exported it back to unity and that solved it
Adressables seem convenient since your app will be downloaded faster if you implement it right (because particular addressables can be downloaded over time, e.g. only content for the current week, so the main app wont weight much).
Alternatively, you could use jsons and store them in some sort of database. It can be convenient in some projects.
Hello, in my script I'm calculating the difference between start and current Rounded mouse position and assigning this Vector3 to my GameObject's Transform. Everything works fine when I assign Transform.position
item.transform.position = position;
But assigning Rigidbody2D.position makes my item go farther from the mouse every time if I move my mouse fast enough.
What's the reason?
item.rigidbody.position = position;
@leaden ice is & or ' illegal character?
\ / : *? ' | are illegal
& is safe?
No
You can assume that any special character except for - and _ is illegal
https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getinvalidpathchars?view=net-8.0 Try the example to see all of them
I love the idea of adressables based on what you said but don't think it sounds needed for this project as my levels are very small json files. Altogether they're only some MBs. I was thinking jsons could be useful but how would I go around making a database efficiently? Still kind of new to these types of things c:
Could be yes
thanks, i'm renaming everything
I think databases are nice for projects that might want to update and/or download the data independently. E.g. you could update levels in external programs or let players upload their own levels. But if you don't need such features, I would probably abandon the idea of database. But if you're considering it, I would probably suggest using Firebase, because it has some support for Unity and there are some tutorials available.
When it comes to addressables, it's worth to mention you can include all of them in the initial build. I also think it would be easier to manage files compared to the Resources.Load.
Make a simple web application that serves the daily puzzles
Thanks for the advice~! It sounds like a database isn't for me but I'm happy for the input about them still.
I'll look into addressables and learn about it as that sounds like the right approach to my situation 😊
is there a way to disable a field in inspector if a given component is on the gameobject?
custom inspector

i would honestly like an attribute to “disable if has component”
I always do the question "Is this gonna benefit me in the long ? is it worth my time making it vs time saved using it?"
or if you're working with game designers I suppose
the answer for me is very much no
so don't do it lol
xd
Can anyone tell me how I can fix these errors?
what is ReferenceChcker?
well that's what's causing your error
you probably want to remove it if you don't use it
yeah
Why is my trail renderer only showing a tiny bit? I have time set to 10 seconds, and it is not lasting 10 seconds. Any ideas?
Also please forgive the extremely blurry second photo 😄
Have you played with the curve? Maybe related
yeah the width curve seems to be set to 0 the whole way?
I have one key, and it's set to .0002
My objects are very tiny
Is that a problem?
Yeah... I'm displaying objects on a map in Unity where the map is 1m, so the aircraft are very small
Sounds like you're trying to sneak your way around doing a real floating origin implementation?
try making your objects bigger temporarily and see if the trail renderer is fixed
just to see if that's the problem
Not really. It's for an AR app. So I have a 1 meter map. And I need to see the aircraft on the map. The aircraft models are tiny. Like .004 meters or possibly smaller
Can anyone tell me how I can fix these errors?
I'll give that a shot and report back
remember floating point precision is about relative values
single precision floats have significand holding the equivalent of 7 decimal digits
but they get sparser/denser depending on the order of magnitude
if the numbers are 1 vs 0.0002, there should not be issues with floating point precision
I tried making the width .01 and the min vertext distance .01, which sould be fine I'd imagine. And I have the same result. Unless it's because the object is moving very small amounts?
I imagine that is likely the culprit
how big is the world?
like, what would constitute a typical big number in the game world
are your transforms at positions with x like 1000?
No they are very tiny. They move like .0001 every second
but what is the actual raw position of the transforms
Changing the trail renderer time to something absurdly large like 500 seems to work. I just don't understand why
if I set prevousHeadRotation = headrotation and headrotation changes...will prevousHeadRotation change also?
Quaternion headrotation;
Quaternion firepointRotation;
Quaternion prevousHeadRotation;
Quaternion prevousFirepointRotation;
No Quaternion is a value type not a reference type
That is the Y value of one of my obejcts for example
ok, so if all the numbers are within a few orders of magnitude of each other, then floating point precision shouldn’t be an issue
awesome thanks! (for the future how to do I determine if something is a value type or reference type?)
just for reference: subtraction is a shitty opperation, because it gets unstable if you have big numbers thag are very close together.
Do you have time scaled?
Let me check, I don't believe so
is there a way to view in editor? Or do I have to log it?
In the Time settings
but if your code is setting it you won't see it there, not until runtime at least
i think I understand now. And I agree with Praetor that your timescale is a likely issue
I have a 2D collider and when a player enters it I set the position of a particleSystem to that player. I'm not sure how to make it work for two players since it switches position between two players in collider.
how do you want it to work for two players?
I want it to create a new particle System when antoher player enters I then want to reference that in OntriggerStay and OnTriggerExit so I can set the position and then delete it.
Maybe I should store the particles in a dictionary and have the key be the players name and value be the newly created particlesystem so I can refer to the particleSystem for that player without interfearing with another players particles
Time to find out if c# has dictionarys
why not just put ther particle system on your players?
Because then the particles behave unnaturally when on player
and rotate with player
that is just a question of organising your hierarchy correctly
If I placed it directly on player it rotates with player so cant have that
There's a few ways to forgo the rotational constraints
When pressing player, my enemy navmesh agent's patrol point seems to moving extremely far away. how can i fix this?
here is the code
!code
📃 Large Code Blocks
Use 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 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.
If I could stop it from rotating somehow it would fix my problem
Parent
--- Player who rotates
--- Empty with Particle System
Steve actually has the best solution if you can go about it, but make your character model and target particle object siblings at most
https://hastebin.com/share/ogitesimel.csharp
Codelink ^
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
sure that works. Of course C# has a Dictionary.
why i can't add 2d character controller
There's no such thing.
Not built into Unity anyway
Ill just use a dictionary then probably bad practice to put a particleSystem in player
so how i make colision with character controller and 2d collide box
What do you mean by "character controller" exactly?
You can make a Rigidbody2D based one
for my case i prefer character controller but i mean the shape
look
Why is my navmesh agent moving very far away from the baked navmesh surface
Pretty typical behavior and I do it a lot. Sticking systems onto player sibling objects that is
i am beginner to 2d unity so idk how to do it
the shape is called Capsule
use a Rigidbody2D and a CapsuleCollider2D
CharacterController is only for 3D
Hello, I still have this issue. Any ideas?
I set Rigidbody2D.position instead of using Physics2D.SyncTransforms(), so I do need to use it for performance
i just realised that i don't need the character controller
i am very dumb
thanks you for the informations anyway
have a nice day
🙂
If I want to destroy a particle stored as the value in a dictionary can I just get the key and destroy it?
Destroy(particleDictionary[collision.gameObject.name]);
yes but you probably want to remove it from the Dictionary too
also you shouldn't use name as the key
just use the GameObject itself
(Know this will throw an exception if the key is not present in the dictionary at the time this instruction is executed)
it's a string as key then particleSystem as value then I'm removing it from dictionary after destroying it
if (particleDictionary.TryGetValue(collision.gameObject, out GameObject particleSystem)) {
Destroy(particleSystem);
particleDictionary.Remove(collision.gameObject);
}```
string key isn't good
names are not unique
and also .name produces garbage
the object itself is a fine key and more performant too
alright so if collision objects are unique ill use that thanks
ooh actually this is probably the cutest way:
if (particleDictionary.Remove(collision.gameObject, out GameObject particleSystem)) {
Destroy(particleSystem);
}```
you don't have to loop through the dictionary to remove key values I thought
Where do you see a loop?
There's no loop here
loops are for while foreach and do : while
Sorry for the delayed reply, but my timescale is 1, it is not changed
As I mentioned previously, changing the Time value in the TrailRenderer to something high like 50 seems to work, but it doesn't make sense to me since my timescale is 1
if (Time.time > ShootConfig.FireRate + LastShootTime Does this not work for networking ?
private void FireNewBulletServerRpc()
{
if (NetworkManager.LocalTime.Tick > GunSelector.ActiveGun.ShootConfig.FireRate + LastShootTime)
{
LastShootTime = Time.time;
GameObject go = Instantiate(TestPrefab, transform.position, Quaternion.identity);
go.GetComponent<NetworkObject>().Spawn();
}
}```
I have the problem on the host the prefab is spawning 10 times ..
I keep having an error saying ""SetDestination" can only be called on an active agent that has been placed on a NavMesh."
Even though I have assigned the robot onto the baked navmesh, How can I fix this error?
Show the code where you call it and the inspector for the object with that script
a powerful website for storing and sharing text and code snippets. completely free and open source.
Code link ^
Navmesh bake
Example NavMesh (source: Brackeys tutorial)
Successfully baked areas will be blue - you don't have any here
But that nav surface component isn't on the ground/plane...
It's on an empty gameobject
What's wrong here
Taking pictures of screens obviously :)
The exception happens on line 193, you're trying to access something on null
I don't have internet right now 😂
Istg 😂
What's wrong with the code. Not my dirty screen lmao
Oh ok I see the second link
for future reference, look below to see how to share !code 👇
📃 Large Code Blocks
Use 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 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.
So is it my hit that is throwing error when there is not a hit?
Hey all, i seem to be having trouble with a BinarySpacePartitioning algorithm, in that i am trying to add a "room offset" parameter that gives some space between the rooms im splitting, but it seems that while it does give me more space between rooms, it's making all of the rooms smaller, which if you turn up the offset high enough, leaves empty/"zero" space rooms. I took the algorithm from a youtube tutorial, and one of the comments bought up this issue, saying that its due to how in the "makeSimpleRooms" function, the for statements are only executed (room.size.x - offset - offset) times. This means that when the offset is greater than 0, it reduces your available space by 2 * offset for both the width and height. The comment mentions that a simple fix could be to include the offset into the BinarySpacePartitioning() parameters, but I'm a bit lost on how exactly to do that. I've tired to add or multiply the dungeon size by the offset, but this still leads to microscopic rooms if the offset is high enough. Do you all have any suggestions? here are the scripts and some pics of the issue, thanks for your time.
https://gdl.space/vibibahiyo.cs , https://gdl.space/oqajizujol.cs
well you've not shared the code in a way that is very readable nor does it have line numbers, so how should we know?
The if is 193
I don't have another way to share it right now. No wifi.
I'm not going to rewrite all the code on my phone to make it more readable
Never mind ill ask somewhere else 😂
This is pointless
okay that's fine. you have the link i provided to you that will help you figure out what is causing the NRE. i don't speak for everybody, but i'm sure most people don't want to try reading a blurry, dusty photo of a screen
Good luck with ur issue
Well u aren't most people. You are you. You gave your input now I am looking for helpful input. You've made it clear you don't want to help if it is inconvenient then asked for help on something else? Ok entitled much 😂
You should be adding the offset to the position, not subtracting from room size.
I think? I'm not fully understanding your code and why you're iterating the number of roomOffset
i should clarify that "oqajizujol" is the actual binary space partitioning algo, while "vibibahiyo" is the driver code that i stick onto the game object to run the generator with the variable parameters
Yeah I see that.
They just asked for line number and said it was hard to read...
And yet they still helped you..
I'm currently just trying to understand the makeSimpleRooms function
ahh i see, lemme rewatch the tutorial i followed and see if that sheds some light on it, maybe i misunderstood something
He helped? I must have blinked
i'm concerned that you seem to be hallucinating. i not only provided a resource that walks you through step-by-step how to troubleshoot and resolve your issue, but i didn't even ask for help either
Yeah, that was a super weird overreaction...
We can still help if you want
Either way, best of luck!
Thought carbys message was yours
@misty ibex Can you try this code and see what happens?
private HashSet<Vector2Int> makeSimpleRooms(List<BoundsInt> roomsList)
{
HashSet<Vector2Int> floor = new HashSet<Vector2Int>();
foreach (BoundsInt room in roomsList)
{
for (int col = 0; col < room.size.x; col++)
{
for (int row = 0; row < room.size.y; row++)
{
Vector2Int pos = new Vector2Int(room.min.x + col + roomOffset, room.min.y + row + roomOffset);
floor.Add(pos);
}
}
}
return floor;
}
But regardless that resource was not helpful 😂 I don't know if it's because I'm on phone or if somehow it's supposed to be helpful that it says the exact same thing that my error line says. All it does is explain what a null reference is. Which I know. But I don't know why I have a null ref
What your raycast hit didn't have a rigidbody, it seems
wait what did i do? 
Attempt to get .gameObject on a null reference throws that exception
Nothing. You asking for help I thought was a message from Box
You did nothing Carby ❤️
Surely you thought to click the links at the bottom of the page to go through the troubleshooting steps
@misty ibex I am curious, what kind of game are you creating?
okay so watching through that part of the video, what makeSimpleRooms is doing is basically going through all the rooms, applying the offset to each room's position, and then adding that possition to "floor" so that can be put in union with the rest of the floor's position hashset
I don't see those on my phone
Box's screenshot is from a phone just fyi.
That's the mobile format
It really is a helpful resource
Have you tried the code I sent above?
Yea ik. Wifi symbol top eight
Right
I apologize for assuming you were being a smartalic but those links don't pop up. I can't scroll at all on my site. Would you mind send me the other embedded links
The second one down should do
Well, either way, there was this answer
#archived-code-general message
Which is certainly the reason for the nullref
im creating a top down shooter rougelite with procedurally generated levels. It was supposed to be for a game jam but i entered way too late and only started working on it at the last minute, but realized there wasn't enough time to finish the game i wanted to submit, so i simply has to withdraw, however, i am going to keep the project as this exact idea was gonna be my first "commercial" game anyways. So it all works out, heh
if you truly do not see those links then you should report an issue on the page. i'm sure vertx would want to know that it's apparently not working on whatever device you are using. click the sidebar button at the top right and there will be a report an issue button
not yet, just wanted to refresh my memory on what make simple rooms is doing
i don't just copy code and not learn from it, i like to learn what it's doing, ya know? but it seems that i coded this part of the generation on a late night and maybe didn't understand what exactly was going on
i am trying your code now
Ah thats cool. Let me know the result of using the code I sent,
I always prefer to code/learn on my own, then I know exactly how everything works. Nothing is worse than going through broken confusing code from someone else.
yeeeaaaaa im confident on my coding skillz but i was NOT gonna be able to figure out procedrual generation on my own, lol
i could maybe learn from reading a few papers but hey, if there's a tutorial on it might as well us that as a springboard
The tutorial is pretty good, just has this one little hiccup. at the very least it helps me understand the algos i need and how to put it all together
that's all development is after all, its all a big puzzle
its all problem solving
For sure
Hey! Right now I'm trying to program in something to stop my camera from clipping into walls in my 3D platformer. As of right now, however, I'm not using Cinemachine. This project is pretty far along so I'm trying not to switch since it would mean refactoring a bunch of code thats already written, so I was hoping I could find a fix that I can implement into my camera as-is?
you would likely need to use physics queries like raycasts/boxcasts/whatevercasts to check when the camera would collide with something when you move it
it's basically the same concept as manually checking for collisions when moving an object without physics
but the better answer, while it may take a bit of refactoring, would be to just use cinemachine which already has some components for that
My camera is set up like this. The main cam is attached to a parent object that has a script that controls its offset from the player. The camera itself has a script on it that allows the player to move it using the mouse and scroll wheel.
just tried the code, and i think i get what you were trying to do, but all i get is a giant ol room
zAdding a collider doesn't work since the movement of the camera is basically teleportation so collisions wont matter unfortunately
Haha
creating a camera is surprising, extremely complex.. that's why something like chinemachine exists 😅
not a code example, but this might help you out with creating a good custom camera, looking at what do to and not do, etc, etc
In this GDC 2014 talk, John Nesky, the dynamic camera designer for thatgamecompany's award-winning PSN title Journey, takes attendees on a tour of all the poor camera choices that he and other game developers have made, and most importantly, how to fix them.
GDC talks cover a range of developmental topics including game design, programming, audi...
I wish i knew about cinemachine when starting this project, would have made this so much easier 😅
yes, this is why i suggested using physics queries like raycasts and not just throwing a collider on it
i'll have to look into that, any good places to start?
i don't know of any specific resources that will teach you how to use raycasts and the like other than just looking at the docs 🤷♂️
i think you are on to something, the issue lies in the MakeSimpleRooms() function
in that i have to find a way to properly introduce the offset. All the offset should be doing is basically splitting the rooms apart from each other
https://pastebin.com/nXGsca7E
The code on the main camera, if it helps
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.
What if you just do this?
Vector2Int pos = (Vector2Int)room.min + new Vector2Int(col + roomOffset, row + roomOffset);```
let me see if that helps
am i making this edit to the original code, or to the edited code you first suggested
as in are my for loops starting at 0 or at the offset
Original code
It should be 0.
You should only be using roomOffset in Vector2Int pos = (Vector2Int)room.min + new Vector2Int(col + roomOffset, row + roomOffset);
Although I believe that is doing what your code edited code would do, just in a different way 🤔
https://gdl.space/apizadinuq.cpp
this is the code i tried but it seems to just lead to big ol room
so i guess starting the for loop at the offset for some reason... works... ???
That is really strange
The only thing I can think of is it being something with room.min
What do you think it is?
essentially, the offset does separate the rooms from each other, but that comes at the cost of the blank space taking up the allocated "dungeon space"
in the comments of the video, someone pointed out this flaw, which is how i noticed, and they called it a "small flaw" that they think could be fixed by using the offset in the BSP() algo
though, im trying to figure out how that would work
Why would it make it look like one big room though?
here's exactly what the comment said:
1) In RoomFirstDungeonGenerator, the function CreateSimpleRooms does not create rooms of the minimum size. Indeed, it seems to me that the loop: for (int col = offset; col < room.size.x - offset; col++) is executed (room.size.x - offset - offset) times, which is fine when offset is zero, but reduces width (same for height) by 2 * offset. The most visible consequence is the reduction in the number of parts when the offset is increased, down to a zero number of parts. I would wait to see the end of the series to remove this small flaw, I think by adding the offset to BinarySpacePartitioning() to take it into account.
i think by executing (room.size.x) times instead of (room.size.x - offset - offset) times, you're basically moving the rooms over by the offset, but not seperating them from eachother
@pearl otter also interestingly enough, with the original code, the for loop runs for about 2200ish times with a offset of 2, but only about 240ish times with an offset of 5... while with edited code you suggested, it runs for 4900 times on the dot, no matter the offset
That is strange. I need to go for a bit but I asked chatgpt and it gave me this code. I don't think it will work but it would only take a second to test.
private HashSet<Vector2Int> makeSimpleRooms(List<BoundsInt> roomsList)
{
HashSet<Vector2Int> floor = new HashSet<Vector2Int>();
foreach (BoundsInt room in roomsList)
{
for (int col = room.min.x; col <= room.max.x; col++)
{
for (int row = room.min.y; row <= room.max.y; row++)
{
if (col < room.min.x + roomOffset || col > room.max.x - roomOffset ||
row < room.min.y + roomOffset || row > room.max.y - roomOffset)
{
Vector2Int pos = new Vector2Int(col, row);
floor.Add(pos);
}
}
}
}
return floor;
}

i appreciate your help but if you're just gonna run it past a damned AI i might as well just figure it out myself
don't ask chat gpt it actually sucks for programming
especially to help others
also, i think it would be helpful if you could tell me your logic/reasoning for your suggested edits, instead of just providing me the code
i really do appreciate your help on this and it's a tough pickle to be in, but i rather stuff be explained to me so i learn rather than just being given the answer
ya know?
let me at least see if it works
if it does im eating my hat
and i don't even wear a hat
it did not work, sadly
yeeaaaa i don't think ChatGeePeeTee is gonna be of much use here
I appreciate it tho, i'll give it to ya that i don't pay for ChatGPT4 so thanks for asking that for me, at least
but no cigar
seems all the code is doing is no producing 2 big rooms that are overlapping each other
wait
actually i messed up the implementation lemme try again
okay fixed my error (forgot to comment out my original code lawl) and....
Yep but thought I'd may as well try as I was about to give up lol
i mean, it's a result