#๐ปโcode-beginner
1 messages ยท Page 118 of 1
Yeah I could add that I guess but this is more of a test
What I mean is, I need to run code every frame on the NPC to increment a number
So it seems unavoidable to call a function on NPC every frame?
incrementing a number every frame isn't that costly tbf
as long as you dont put some huge blocking logic inside the Update() function you should be fine
Yeah, just changing a number in update is essentially nothing.
That's normal. Its not a problem . . .
There is also a method to InvokeOnce if I remember correctly. But I've never really used it, just seen it on a few videos in passing.
Imagine a FSM or behaviour tree and 1000 npcs, do they run all their state machines every frame for every NPC?
If your npc is not active then the Update function wont run
Each state can have an update interval/tickrate so they don't have to update every frame anyway
also if your Update function has something as little as modifying a state of a counter then its fine tbf
Anything that is in Update() runs every single frame, even calling other methods/functions etc. So (and please someone correct me if I'm wrong) CoRoutines and the like are more desirable as they take the 'load' off the constant updating.
I'm still learning so I get a lot of things wrong, but I always try and keep my Update()s as empty as possible.
It does not run every single frame. It does not run if gameObject.activeSelf == false
@queen adder I was assuming when active.
Oh
I thought the only time he needs npc's to NOT run update is when its active = false
Well I think they will always be active because I need to know when NPC has finished sleeping
A coroutine internally checks a timer every frame to determine when WaitForSeconds has expired . . .
Unless I make a clock and wake up all the sleeping NPCs with a schedule
Ah. I understood it as, NPC's are performing tasks throughout the game, when task A is finished, move on to Task B etc. etc.
Yeah they have a life cycle
yeah defo sounds like you should use coroutine
So after the npc is awake you dont need to run the counter?
Okay, so sleeping is essentially a Task. So yeah either a timer (like in the video I posted, old, but works), or coroutine.
esentially be like this:
public IEnumerator WakeNpc() {
yield return new WaitForSeconds(_secondsUntilNpcIsAwake);
DoSomethingAfterItsAwake();
}
!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.
Use a variable as a timer, a timer class, or a coroutine. Those are your options for tracking time and execute a method afterwards . . .
Idk what timer task you are talking about but whatever you do, do not use a the timer in c#
It spawns a new thread
You could even do something like.
public IEnumerator PerformTask(state Task, float taskDuration) {
//Change task to the one gotten from above
yield return new WaitForSeconds(_taskDuration);
SelectNewTask();
}
Maybe?
nvm i was wrong this is java TimerTask
Get mixed up a lot
if they're running logic on a ton of AI's, I dont think coroutines like this are a good idea. Itll create a ton of garbage
Not sure what your Tasks are stored as so edit accordingly.
The coroutine will nicely handle states and instances for you though, if you opt for the coroutine - has a cost of some memory allocation for managing the state/instance.
I meant a custom Timer class. I ended up creating my own Timer package for this very reason . . .
You can do a proper nice coroutine design .e.g. 1 coroutine for several npcs:
public IEnumerator WakeNpcsUp() {
var firstNpcToWakeUp = Npcs.Min(t => t.WakeUpTime);
yield return new WaitForSeconds(firstNpcToWakeUp);
//calculate which npcs are awake
}
So your coroutine wakes up the earliest npc. You'd need the while loop in there too
Instead of 1000 coroutines, 1 coroutine checking the min time required to wake the first npc up
Not sure what the original problem was tbh
Cache the yield statements if possible as well unless they're one time use disposables.
He was doing it in the Update() function
so the logic would call regardless every frame
was it possible to show a variable in the inspector but not make it editable? just so i can see that it changes
I think you want something like this
https://www.patrykgalach.com/2020/01/20/readonly-attribute-in-unity-editor/
Not built in AFAIK
All serializable values should show up in debug mode
yeah i know but wondering if it is possible in normal mode
. not possible out of the box
You need to add extra code
Or assets like Odin inspector read only etc
Yeah, that's the whole point of the page I linked
Easy to find a ReadOnly attribute online or write your own. Very handy . . .
NaughtyAttributes also has it https://dbrizov.github.io/na-docs/attributes/meta_attributes/read_only.html
why do people do this in unity :[
[ReadOnly]
public Vector3 forwardVector = Vector3.forward;
I know its longer to add [SerializeField]
But its equally as ugly seeing public variables all over the place
Even if i needed something to be public i'd do:
[field: SerializeField]
public string A { get; set; }
never public string A;
I didn't know people did that. If given access to other classes, it's preferable to use a property . . .
I've never seen anyone do this. Is that from NaughtAttributes or Odin?
It's in the naughty example
just this link over here in an example. Ive seen many other packages follow the same style
Probably just for readability
Oh - probably just to show off the attribute
hey, i wanted to ask how would you handle this issue for a competitive shooting game?
cause torque interpolates right?
That makes sense. You can't really show how it works if you use a property . . .
i assume you can do this: [field: ReadOnly]
Can't use { get; set; } with Odin
or show their example like such:
[field: SerializeField]
[field: ReadOnly]
private string A { get ; set; }
you guys not seen use of public class variables all over in unity?
I might be downloading bad packages then
๐ญ
only beginners (or the lazy) do this ๐
they're all over the docs though
Torque doesnt interpolate, it just rotates. That's what torque is. Im not entirely sure how current games handle it, but mostly they arent using rigidbody movement (or unity) to begin with. Just directly rotating the player should be fine since those games dont require accurate physics in that sense, and you want it up to date with mouse input
It is just an example, even the unity docs have some shit code in their examples.
Sadly bawsi :\
People follow these examples and end up writing public all over the house
Show people the correct way they'll do it the correct way ;D
but to make such game in unity you'd have to use a rigidbody though, right? a lot of people say charactercontroller is bad (also it forces you to use a capsule collider) and making your own solution from scratch requires you to basically recreate all the physics a rigidbody offers if you want to interact with physics objects
Lots of packages or assets can be made by beginners anyways. Like I tried out one AI asset from the "23 for 23" bundle recently and it was absolutely written by a beginner who had a decent amount of time. GetComponent calls everywhere, ton of garbage created
I only recently realized that we could do [field: Attribute]
Before i was doing:
[SerializeField]
private string _a;
public string A { get => _a; }
You'd use the appropriate tool for the job
so if i want the player to be able to push physics objects and stand on moving platforms, the tool for the job is definitely rigidbody? or something else?
You could use a rigidbody, could make a custom character controller. Not really sure what answer to give you, because all the current competitive shooting games I know arent made in unity to begin with
one that comes to mind is tarkov (idk how competitive that is but its a shooting game)
You can do any of that with a custom character controller as well.
Rigid body component is for rigid body physics - you'll get basic physics and more (sliding, friction, ragdoll and whatnot)
but by making a custom character controller yourself you'd have to manually do all the interactions with physics objects, like pushing them and standing on moving objects and such. but with rigidbody it comes out of the box, right?
What if you don't want some of the features from Rigid body though?
You would also push players if you arent careful. Which can really suck
Backend server side integrates with unity assets
Like how gravity applies to a rigid body on a slope (sliding) or how fall speed (terminal velocity) isn't game-ish enough
It's great for simulating physics behavior with objects though - rolling a ball, firing a cannon, sliding a box and whatnot.
.e.g. my component can have something like this attached onto it and from my server side code i can get this script and change state of it, it reflects on the client too
It just works
Looks unsafe
very :]
wait but im talking about a kinematic rigid body, is that different?
wow multiplayer looks complicated. does one have to remake every script from scratch to be able to turn a game multiplayer?
well if you use something like photon quantum you want to make all your entities using the EntityPrototype component script
You dont need to re-write all of it, just the bits where state update is required and the update is on a multiplayer level
.e.g. if i was firing a bullet i'd not instniate it using the unity client i'd use photon systems (server sided) and use frame.Create(projectilePrototype)
This way all users can see it
interesting
Hey, guys! I have a question. How to choose display mode(Windowed, Fullscreen) with a dropdown, I mean how to make the functionality work when someone want to choose in dropdown for example full screen?
I have seen videos of how to make full screen to work with a toggle but dont know yet how to make it work with dropdown
photon quantum is expensive btw well atleast i think
0.5$ per ccu
I had to write a pre-lobby system so people dont automatically connect to photon lobby
It saves $
but all the character controller scripts you find on the asset store are rigidbodies, and called like "kinematic character controller". seems like nobody has made their own character controller
wait it costs money for players to be able to play multiplayer? dang
:/ I know. I've made a few game servers in the past and to get them to handle load reliably is a really difficult thing to do
They are offering the reliable photon cloud
No netcode too. So i dont need to worry about shit like endianness
What is the most efficient way for enemies to detect players in a given range? Because the only option I can think of is if every enemy had a script that constantly measured its distance from the player. But with a lot of enemies this seems a little stupid?
thank you!
a-star algorithm for 2d, navmesh for 3d. am i right that those are the best options? (not an expert)
I'll research that thanks
@terse ravenCould also run a trigger on the enemies, not sure how performant it is tho
You can do something like this:
Collider[] hitColliders = Physics.OverlapSphere(center, radius);
Or overlapshere on the player and see what they can find
Are there any downsides to pausing using timescale = 0? Last time I did this it paused the entire GUI, but that doesn't seem to happen now. I still need to use GUI, and do script stuff
I need path finding too because of top down game lol
2d top down cant use navmesh tho
if its 2d u gotta use something like a-star algorithm right?
oh 2d i c
not sure if a-star algorithm is the best though
whats this?
I manage to use navmesh fine with 2 axis's :\
But i assume they cant form the navmesh
Cause sprites are not models
can u actually ask ur question again on #๐คโai-navigation to get a confirmation from experts on this
sure!
You can generate a navigation mesh which tells your game this place is walkable and this place isn't. You can find this in your navigation tab and tag different components as walkable or not.
@terse raven you're talking about a 3d game right?
Tile clipping in a 2d game will be different
nope 2d top down
Ok so you dont need a nav mesh
tile clipping then?
well i think the answer is a-star algorithm but id also want to hear what is said in the ai-navigation channel to be sure
yeah basically you'd use the A* which denotes a tile like this:
clippingFlags[hash(x,y)] = flag;
where flag can be NORTH_BLOCKED | SOUTH_BLOCKED | EAST_BLOCKED etc.
Each coordinate has a clipping flag where you can block certain directions. From this the A* algo can work out the best route to take to a coordinate
Best asking #๐คโai-navigation the best way to do this in unity
do you recommend making a new character controller system from scratch and coding stuff like hitting walls with raycasts, and being able to push rigidbodies and stand on moving platforms and such?
or is rigidbody recommended
cause a lot of people recommended rigidbody so idk
hello!
i have a gameobject that has 2 child trigger colliders. is there a way to check onTriggerEnter/Stay/Exit which child got triggered from the parent script?
or at least make it so that the parent ignores the second trigger's collisions
but keep it as its child
You can't
You can just do the OnTrigger in the child objects and choose whether to bubble it up to the parent or not.
But the parent rigidbody will "see" all child colliders as the same compound collider and cannot differentiate between them automatically
what do you mean bubble it?
Have the child script call a public method on the parent script or something
Bubble up just means lower tier (child) entities tell the entity above them, which tell the entity above THEM, and so on.
void RemovePreviousRoom(int index)
{
moveable.RemoveAt(index);
}```
i'm trying to remove an element from a list and i get this error. is there an easy fix for this?
your list is null
sorry, i'm not sure what that means
your list doesn't exist
and you cannot access something that doesn't exist
Where do you assign a list to the variable movable?
i see, thank you
under a switch statement in another method
Well, it may not be hitting that switch value.
is it local variable then
wait i'm really dumb hold on
Hello guys, i have a scaling problem i want to be able to move objects from my inventory based on the current mouse position but when i use the Input.mousePosition variable it doesnt actually match with the screenspace even after dividing through the scales of the parent components im not sure what im missing
[SerializeField] private RectTransform rectTransformItem;
[SerializeField] private RectTransform rectTransformUI_Inventory;
[SerializeField] private RectTransform rectTransformCanvas;
[SerializeField] private RectTransform rectTransformItemSlotContainer;
private RectTransform rectTransform;
private bool clickedSlot = true;
private void Awake()
{
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
if (clickedSlot)
{
//Debug.Log(UnityEngine.Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -10)));
Debug.Log(Input.mousePosition);
rectTransform.anchoredPosition = Input.mousePosition / rectTransformItemSlotContainer.localScale.x / rectTransformCanvas.localScale.x / rectTransformUI_Inventory.localScale.x / rectTransformItem.localScale.x;
}
}
i don't believe so, also i made it create the list at awake and now i'm getting this error
so now you have a list, its just has less elements than index you're accessing
show full !code
Hi i have a problem with my gravity tool because when i use my tool wheel to activate it then my tool does not work and when i activate it in the inspector it works and the tool wheel just activates the script on the player using
toolScripts[index].enabled = true;
and the script gets enabled it just dosnt work like it should and the LightTool works fine using that method of enabling it (no error in console)
https://hatebin.com/strquwmqas ignore my absolutely horrendous switch statement, i'm not great at optimizing yet
what is this line of code supposed to help with debugging..
toolScripts[index].enabled = true;
i dont know
also show the full stack trace plz
(i hope i'm not mistaken about this being the stack trace)
๐คทโโ๏ธ depends really on the game. im sure you would get the most customization with a custom system but this isnt really something easy to build at all
you have to select one of the errors
is this correct?
yes
bad screenshot oops
its this moveable.RemoveAt(index - 1);
you're removing at index that isn't in the list
ahhhh
i'm fairly new to lists so i can see how i would make that mistake
does this mean that i have to change how i get the length of the list?
make sure you have enough elements before doing RemovePreviousRoom(enemyRoom);
its literally guess work from this side at this point..
thanks a ton, i'll figure out a way around this
does anyone have an idea?
You should use these instead:
https://docs.unity3d.com/ScriptReference/RectTransformUtility.PixelAdjustPoint.html
https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html
https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToWorldPointInRectangle.html
I have made a tool system for a game and it works but after it enables the tool script i need to press again and then the tool script works
please see #854851968446365696 for what to include when asking for help. nobody knows wtf you're talking about without more context
but what Context do you need
how about literally any context? what is a "tool system" what does it mean to "enable the tool script" what are you "pressing", what does it mean for it to "work", how are you accomplishing any of this. nobody here can read your mind, mate. nor can we see your screen
chill
your input is not needed. but if you feel they've provided enough context with that one message, then go ahead and answer their question
oh yea sure the tool system is where you hold tab and then a radial menu comes up then you press the tool you would like to use like the Gravity Tool then if you press it enables the script On the player and the player has this inspector and a rigid body and collider but when you select a tool you need to press again after the tool is selected (the script is enabled like the gravity tool script) and then the gravity tool script works like you can pickup objects and rotate and place them
don't forget to also show your !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.
Code was here
What do you need to press again? The tool button in the radial inspector?
the start btn ๐
Just the left mouse button
where are the methods inside of the ToolWheelButtonController being called?
In the ToolWheelButton under Event Trigger
Wouldn't this then mean that the tool is fully enabled in gravity tool at the if statement at line 49?
look at line 46 it says ```cs
if (isHoldingObj)
Do you want it to start holding after the tool is activated in the tool manager?
You pickup stuff using E but when you have selected a tool you need to press Left mouse button for the tool to work thats my problem because i want the tool to work when you select the tool
that with the gravity tool if you press E after just selecting the tool and not pressing LMB it does not detect you are pressing E
When you press E does it run ActivateTool in the tool manager?
Wait nvm
you should put some logs in those methods on the ToolWheelButtonController to see when those are being called
and it is only after that Deselect is called that it starts working?
or are you not fully testing it to see the full picture?
yea it is
NVM works now i just added Deselect(); down at HoverExit
like this
public void HoverExit()
{
Deselected();
Debug.Log("Stoped hovering over tool with id " + toolID);
animator.SetBool("Hover", false);
toolText.text = "";
}
yeah i have a feeling it's because you are constantly enabling/disabling the component until Deselected() has been called
why is that?
okay after testing it, that is exactly what is causing this
[DefaultExecutionOrder(-100)]
public class TestThing : MonoBehaviour
{
AnotherTest thing;
// Start is called before the first frame update
void Start()
{
var go = new GameObject();
thing = go.AddComponent<AnotherTest>();
}
// Update is called once per frame
void Update()
{
thing.enabled = false;
thing.enabled = true;
}
}
[DefaultExecutionOrder(100)]
public class AnotherTest : MonoBehaviour
{
private void OnEnable() => Debug.Log("Thing was enabled");
private void OnDisable() => Debug.Log("Thing was disabled");
private void Update() => Debug.Log("Thing updated");
}
not a single "Thing updated" log was printed for the duration of the test
instead of calling ActivateTool every single frame until the object has been deselected, only call it when the object is selected
Hi there, I got this script, and it is supposed to decrease the enemy's health when colliding with a game Object with the tag "Attack". Yet nothing happens? The tag is the same, and is attached to the attack.
how would i do that because this script under is the activation thingy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ToolWheelController : MonoBehaviour
{
[SerializeField] private Animator animator;
private PlayerController playerController;
[SerializeField] private ToolManager toolManager;
[SerializeField] private Image selectedItem;
[SerializeField] private Sprite noImage;
public static int toolIndex;
void Start()
{
playerController = Camera.main.gameObject.GetComponentInParent<PlayerController>();
}
void Update()
{
if (playerController.toolWheelOpen)
{
animator.SetBool("OpenToolWheel", true);
}
else
{
animator.SetBool("OpenToolWheel", false);
}
switch (toolIndex)
{
case 0:
selectedItem.sprite = noImage;
break;
case 1:
toolManager.ActivateTool(0);
break;
case 2:
toolManager.ActivateTool(1);
break;
case 3:
toolManager.ActivateTool(2);
break;
case 4:
toolManager.ActivateTool(3);
break;
}
}
}
I mean its like this
collision.gameobject.tag == "tagName"
boxfriend just a question after we fix this loop thingy is why is this code wrong
or if you cannot conceive of how to only call a method one time instead of every single frame you could just loop through the objects inside of ActivateTool and set the enabled property to i == index so you're not disabling the one you want to keep enabled
the CompareTag method, which is what they are using is better. not only will it throw an error if a tag is spelled wrong/doesn't exist, it is actually a bit faster too. what you've suggested is slightly worse for performance and will fail silently if you've made a spelling mistake
huh?
so it's not that it is wrong, it's just less correct than what they have
this is not a helpful response
oh well my teacher has like a Tags.cs that will help do so we can have multiple tags on 1 item and dont make spelling mistakes
yea it is i just dont understand the รฌ == index where that is
I have to admit I am a total noob and I'm not understanding anything rn tbh ๐
i provided a link that will walk you through everything you need to check to ensure that OnCollisionEnter is being called. have you gone through that?
I am trying
okay well keep in mind that nobody here is a mind reader so if you do not understand something you are seeing on that site, then you have to ask about it
Is your game 2D or 3D? Because 2D games use OnCollisionEnter2D()
It's 3D
Alr
still nope ```cs
public void ActivateTool(int index)
{
for (int i = index; i < toolScripts.Length; i++)
{
DeactivateAllTools();
toolScripts[index].enabled = true;
}
}
did you even read the entire message?
Hi there, I got this script, and it is
yea i did
instead of calling DeactivateAllTools (which is where you are disabling all tools, including the one you do not want disabled) you use that loop and for every iteration of the loop you set toolScripts[i].enabled to i == index
and why are you even starting the loop at index.
i am sorry i am so tired right now can you try and explain it for me
NVM
ITS WORKING
public void ActivateTool(int index)
{
for (int i = 0; i < toolScripts.Length; i++)
{
if (i == index)
{
toolScripts[i].enabled = true;
}
else
{
toolScripts[i].enabled = false;
}
}
}
i know, because you are no longer disabling the component every frame
also you can literally just do toolScripts[i].enabled = i == index;
but this is more readable for me
you don't need the if/else because i == index evaluates to either true or false already. and you're assigning to something that expects one of those two values
g'day guys, I'm super new to coding, what do you think is the best FPS movment I could do, I have tried a lot of tutorials they just have not worked.
they just have not worked
do you mean to say that the movement was not satisfying for you? because if you mean that the code you got from the tutorials didn't work then you didn't pay enough attention to whatever tutorials you followed because there's no reason they shouldn't work, unless you're looking at some truly terrible tutorials that nobody else has followed
sorry, I should have explained better; It's almost my Visual studio is different from there's I have the unity game developer thing on it, and development with c#.
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
but that will also not make the tutorials just not work, it just won't provide syntax highlighting, error underlines, and autocomplete
thank you, also, when I was doing a launcher script, (followed a long tutorial for it) it didn't work because the photon stuff just will not show up while I am coding
it gets super annoying because it gives me 11 errors when i finish
don't do multiplayer if you don't know what you're doing. you're going to have a bad time
It's realy what I wish to do, so I can test it and have fun with friends and all that jazz
sure, but learn what you are doing first
you're not gonna go race a formula 1 car before you've even learned to drive. so don't do multiplayer before you've learned to make literally anything
thanks for the advice
I will just try to only movement
and try all of that stuff
Hi guys very new here. Iโm working on a 3D breakout game called Cubix. I have the paddle and blocks programmed and a score displays. Iโd like to have scores persist. API call to my own website?
How is authentication and authorization normally handled in Unity web gl games?
Hey, is there a way to detect npc movement?
Be more specific
i have an npc that follows my player, i need to detect when he moves so i can make that when he moves he starts doing his running animation
How are you moving it
I made the movement, I took my time and thank you for this advice
How do I create the input settings asset? The xxxx.inputsettings.asset
check the docs pinned in #๐ฑ๏ธโinput-system
What's the best way to create a canvas and add text to it in script
@slender nymphOkay I found it, but it still does not find my mouse and keyboard
i have no idea what you are referring to with that last part ๐คทโโ๏ธ
I have a value that gets incremented by Time.deltaTime every frame (in Update()), how can I call a function every time this value is a multiple of 5? In other worlds, how can I call a function every 5 sceonds?
this is a code channel mate. if you have questions about setting up the input system then ask in #๐ฑ๏ธโinput-system
Already did
whenever it gets to or above 5 call your method and subtract 5 from it. or if you cannot subtract from that specific value, then have a second float that you also add deltaTime to and use that
because the alternative would be to FloorToInt the value, % 5 it, check if you've already called the method for this specific multiple of 5 and if not you call the method
Something like this:cs while(timeValue >= 5f) { timeValue -= 5f; MyMethod(); }
I used while instead of if so that if you get lag and it goes to for example 10+ seconds, it executes it twice
Alright, thanks
You can also use a coroutine to do the delay
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gatomilowmovimiento : MonoBehaviour
{
public float speed;
private Transform target;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
im searching in docs for a way to make the npc dont touch the player tho
So, the NPC moves any time target.position is not equal to transform.position
I made it, thx, that was actually a nice way to guide me without telling me exactly what to do
Can someone help explain the difference between Update() and LateUpdate() and how LateUpdate() works?
See the 'Game Logic' section of the graph here:
https://docs.unity3d.com/Manual/ExecutionOrder.html
Simplified: First all Update() methods in all monobehaviours are called. Then all LateUpdate() methods in all monobehavoiours are called. Both are called before the frame is rendered.
This helps a ton, I appreciate it. Exactly what I needed to know!
is there a way for making the npc only following the player in the x axis?
Instead of moving towards target.position, move towards a position that is target's X position, but this object's Y and Z
transform.position = new(target.position.x, transform.position.y, transform.position.z);```
i made it like this, but the npc is sticking to the player and i want it to follow him
@queen adder You might need to add an offset so the NPC is not trying to match the Player X position.
@queen adder Or you could do an distance check within the NPC component
What happened to MoveTowards
How do you usually work around player getting crushed by platforms and clipping into the ground?
Right now and just did a false safe that tps the player up if they get beneath the ground :p
Do you prevent the player to ever get beneath the platform? Do you create a collider beneath it that stops the platform movement if the player is in there? Do you just kill it?
I am kinda curious what is like the default thing to do here
More of a design question.
If you want it to be forgiving, stop/reverse the platform when it hits the player
If you want it to be hardcore, kill the player
Checking if an object is "squished" between two objects can be tricky, though
Yeah, like I was wondering how could I detect the player is in position of which they should be "crushed"; like maybe like create an smaller collider inside the main player collider that while in contact with another collider which is not the main player collider would mean that he is clipping and should be killed?
Seems kinda messy, can't really think of much more to be honest
Maybe make a raycast from the platform down to the ground and if the distance is equal or less than the height of the character, consider it crushed.
Obviously, the raycast would need to ignore the character layer.
And it's best to make that check when the platform already collides with the player.
Im having a problem with this script for my looking in my FPS game, know how to fix?
make sure that your !IDE is configured so that it will underline errors
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
its giving me an error with my UpdateCursorLock();
yes because that's the line you declare the method and it isn't abstract so it needs a body
can you explain better for me?
what is different about that line compared to any other line you have a method on
That wouldn't crush the player even if they are not even there?
like {}'s?
That's why you do it only when the platform already collides with the player.
almost there. but pay attention to that line specifically
void?
That woul kill them if they are on top... right?
maybe the update would be before
no
im stumped
I guess you could also make a check that the player is colliding from the bottom of the platform.
Unless you have situations where it can get crushed between the ceiling and the platform too.
I dont knw whats wrong
look closer
Basically sounds, like you want to go over C# basics.
I mean, it depends of if you want to make it just a single case think or a whole integral part of the game how you would code it
It might be impossible or very hard to make it fit every case. Does it worth the effort if you're never gonna have such cases in your game?
sthrdrt hert yhurhjg
In Little Big Planet for example you could be crushed from any force in any direction or conbination of forces in different directions if it was enough
I mean, not really, but is always worth trying to make some script as modular as posible so it can be reused later
Alright, here's a quick fix: check that the platform velocity direction and the the direction to the player align before making the raycast.
I actually kinda have an issue with that for a while with my "mini-test" game where the player moves based on forces and the plataforma just use a translate, so I don't, think they have a velocity at all
HMM i wonder
Velocity is an abstract thing. You can keep a track on velocity even with translate.
object p = UpdateCursorLock();?
But here's another way:
Keep track of what your character collides with and from what direction. When it collides with 2 objects from opposite directions, consider it crushed.
well now you're just taking random guesses. please see the beginner c# courses pinned in this channel
not a guess :( visual studio dumb i guess
I think I could send a raycast from the player up to check only for plataforms and down to check for any valid ground and check that they both return a hit that is at least half of player heigh away from the origin, if they aren't, that means they are clipping
void UpdateCursorLock();
and what is wrong with that
The intellisense would do it's best to make suggestions that make sense in the context of the code. It doesn't know your intention, so it might guess it wrong. That's why you need to understand the basics.
Doesn't sound more generic than my previous solutions, but if it works for you, go for it.
Wdym by "semi"?
anyone aloud to ask question in here?
Not aloud. You can ask quietly though.
whats that mean lmao?
English mf, do you speak it?๐ฌ
yea its my first language you?
Is pretty generic, indeed; I think you could do the same with left and right and have a system that could maybe work at detecting crushing for any side??? I am not sure, sounds kinda cheap tbh
It's not my native language, but allowed and aloud is not the same thing.
That's what my last suggestion would do without any extra logic.
If you're specifically differentiating between sides, it makes it less generic.
yea grammar isn't my stong side but i get the joke
So you are suggestions to keep track of anything that collides with player and its velocity?
Anyways, you don't need to ask for permission to ask. Just make sure it's the right channel.
Collision direction, not velocity.
How can I even detect the collision direction?
I didn't know you could do that
I'm pretty sure this is the right place,
Many ways, but I think you get the contacts info from the Collision object and use it's position to get the direction. Or relative velocity.
Rigidbody enemyBulletInstance;
enemyBulletInstance = Instantiate(enemyBulletPrefab, enemyFirePosition.position, enemyFirePosition.rotation);
enemyBulletInstance.AddForce(new Vector3(playerPosition.transform.position.x, playerPosition.transform.position.y, -5f));
the enemybullet fires from the correct spot but has the wrong trajectory. how would i fix that?
Oh so like, onCollision I get a vector of the position between the object and the object it collided with; and then.... what? Like this seems like way beyond my knowledge rn
have a good one i know the feeling
i still don't understand why im so dumb after going over 5 different courses of coding
And then you cache it(add to a list for example). Might be a good idea to create a plain class or struct that contains all the required info and cache it.
cause every dang time people say, "go over basic knowledge of c#" WHEN I HAVE
I JUST CANT FIGURE IT OUT
Then also check if there are already and cashed collisions. And if there are, make the crush check.
IM FRIED
Break it down. Analyse the things that you're having difficulties with and research then separately. Or all about them.
!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.
im still pretty fresh i just started for the day, i normally feel like that after a long day and trying to fix an issue so your not alone.
I've asked multiple people went through the roll-a-ball course to try and fix 1 line of code, and after all of it I still can't, and people know and wont even tell me
I have been up since 2Am until now coding, Im not stopping
until
then start with the basics of c# outside of a unity context.
Sry, this is clearly surpasing me, I have not "cache" anything yet. But like when do you say they collisions should be removed from the cache then; do I just check all collisions each frame and then deleted them?
Perhaps the courses you went through were bad, or you didn't concentrate, or it's just not a suitable learning method for you. Hard to say.
also yes, that was the issue
On collision exit.
To cache just means to save/keep track of some data/references for later use.
and now i import the lines of code..
unity?
i made the script
now importing?
https://gdl.space/juculatiju.cs like this?
wdym by importing?
im fried bro
then take a break. i don't know what you want me to tell you ๐คทโโ๏ธ
i've been pushed around all day and my eyes are super bluuryy
so yeah now I can
taje a vreak
But... you would need to take the collisions reference Onstay, not just on enter, since stuff can move around while on contact with you, how do you exactly clear the cache on exit? And how do you exactly do the crush check anyways? Like you go with each collisions 1 by checking if there is any collision on opposite direction with one of them having enough velocity towards the player?
You can update the cached data in OnStay and remove it on exit. I don't see a problem here.
The crash check would loop the cached data and check if there are 2 collisions with directions(dot product) being close to opposite.
Yep, definetly more advanced that what I can do now, I still think doing a single fucking spheres Cast to. work is complex enough
Well, you'll get there eventually. It would be pretty simple for you at some point.
Actually, you're probably confused by dot product? It's not that difficult if you research it. It's just a Vector operation. Very handy too
guys idk where to start with game development, man
like I know what I want to make
but I just like
have no idea how to do it and its at a point where I'm in "uncharted territory" and there arent gonna be any resources for my specific issue
if that makes sense
actually you know what? Is chatgpt reliable in helping me with game development? Like can it help me make a game for me
anyone have any idea about that?
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
This is when you take the things you have learned and why they work and combine them into new ideas
anyone have any idea about that?
Yeah, it sucks, and most people here hate seeing any question that's arised from it, answered with it, or related to it
haha I'm not a fan of learning that way, I just like to jump in and learn as I go but I think I'm at a point where I need to do this now
dang
I have a Bullet class that has a simple OnTriggerEnter callback to destroy the bullet. Sometimes it works, sometimes it doesn't. Not sure why. I am firing the bullet at the same wall, the wall has collider, the bullet has collider and is marked as Kinematic and Is Trigger. Its Collision Detection is set to Continuous Any ideas?
I'm reading up about Scene Management and additive scenes and I want to be able to unload additive scenes that are no longer required.
I'm aware of the function UnloadSceneAsync however it says in the description the following:
Destroys all GameObjects associated with the given Scene and removes the Scene from the SceneManager
Just to clarify about the bold section, does it simply mean that the additive scene is removed from the Main Scene hierarchy?
So in theory, I can load that additive scene in again if I want?
I'm not sure you can unload an additive scene. It kinda merges with the main scene afaik.
Sure you can
removes the Scene from the SceneManager
It just means you can't find the scene via any of the GetScene functions
because it's not loaded any more
ahh right, so If I want to do anything with that scene again, I'd have to reload it back in additively.
cheers!
Oh really? I always thought that part of unity was a bit underdeveloped, but I guess I didn't get into it enough.
hey, we all learn new things every day
For sure
https://gdl.space/yomofabaqa.cs this is the code from the #๐ปโunity-talk channel
Your bounds includes 0,0,0, are you sure you want that?
whats it do?
Bounds combinedBounds = new Bounds(Vector3.zero, Vector3.zero);
Your bounds starts at 0 always, ie. it has encapsulated Vector3.zero
Pasted it into a better site: https://hatebin.com/qjbtqtqbhz
In gdl.space the comments are the same colour as the code so it's really unreadable
why is this doing nothing? it doesn't even print i?
They are different colors to me ๐ค
๐ค
i = 10, which isn't < 10, so the for loop never enters.
because it only runs when i < 10 and you are setting i to 10
@north kiln Oh it's my dark reader extension causing that lol
๐
nono, how do i make it so the boundarys encapsulate the green platform
set int i = 0
๐คท
for 10 loops
Type for and autocomplete it to create a for loop
instead of manually typing it out like a pleb
forr for a reverse for loop
@shell osprey I gotta ask, are you using ChatGPT?
yeah ๐ญ
Don't create a default bounds, only initialise it when you set it to the first bounds
I personally made a NullableBounds struct for myself because I hated that ๐
You shouldn't be using bounds for that anyway. That wouldn't prevent the objects from spawning in the holes between the meshes.
how do i go about fixing it?
You'll need a different solution. Since you're using chat gpt, try telling it that there is an issue with this approach.
it gives me a new script that changes nothin
is move towards a lerp or a teleport?
Neither, it's a move towards
Did you explain it what the issue was? Also, don't expect it to give you a whole script. Instead ask it how to implement it. It shouldn't replace you as a coder, but help as an assistant.
oh well now I have no questions
alr ill try that
it helped except that not all of them are being randomsied now
It neither lerps two values nor teleports anything. It is CLOSER to lerping plus increment code I guess if you have to pick one. Teleporting isn't anything like it though.
Lerp nor MoveTowards (despite the name) have anything to do with movement by themselves
What did you change
You don't know what lines changed?
Seems like you are just blindly copying from ChatGPT and then asking us to fix it
Instead of trying to understand what's going on
guys im making a weapon recoil but it seems to not work,anyone knows which thing is bad?```
public class WeaponRecoil : MonoBehaviour
{
private Quaternion initialRotation;
private float randomRot;
private void Start()
{
randomRot = Random.Range(initialRotation.x - 1000f, initialRotation.x + 1000f);
initialRotation = transform.rotation;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
transform.Rotate(randomRot, 0, 0);
StartCoroutine(BackToNormalRotation());
}
}
IEnumerator BackToNormalRotation()
{
while (true)
{
setRotation();
yield return new WaitForSeconds(1);
}
}
void setRotation()
{
transform.Rotate(initialRotation.eulerAngles);
}
}
This needs to be mostly re-written, most of it is bad. Follow a tutorial or something
yeah and hoping it works
ok thank you
So you are putting nearly zero effort into learning or making the game, apart from asking questions
This is a totally inappropriate way to get help on the discord, so much so it goes against our #๐โcode-of-conduct
- โข Use unverified AI-generated responses in questions or answers.
It will not
hello can some1 pm me i need help with something
No, just ask your question
im having issues with some code from one of the brackeys tutorials and cant seem to get around it
Describe the issue specifically and post the !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.
wdym post the !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.
Read the bot message and post the code.
You just triggered the guilde. Follow it and add the code.
Guys. I'm now working with Dialogue System with Ink intergration. Now one component I need to add is voice acting and background music. What should I do now?
after ive written it what do i do
What do you mean "what should I do now"? Like how to handle voice acting and bg music?
In a paste site?
ye
Yeah, that one
There will be a save button. Click that. Then copy the url and paste it here
Do you want the code? I'm going to post them here if you want
Sure.
I was gonna say that you just need to have the sound file linked to the text. Structs or SOs are good. When you bring up the text have the audio source play the sound file
For bg music, I like to just stick a source on the camera and have that play the sound file
You need using TMPro; at the top
like add that or change it for one of them?
Change it for one of them?
It's a using directive. It's a line to add
You should already have a few lines that say using
It's just like that
okay thanks
Well this is the DialogueManager script. The script is too long now I can't actually copy and paste to discord :v
!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.
The code is too long. I can't add it to discord.
Look at large code blocks
Got it!
What are the best practices for components of a gameobject? Like should I make a variable for the rigidbody or just call GetComponent every time? Should I make the variable public or private?
GetComponent is very expensive, make a variable at awake
you should definitely not call GetComponent every time. Cache it in a variable if you're going to use it multiple times
GetCOmponent is NOT very expensive but it's still not something you should do constantly
and there's no reason for a field to be public, pretty much ever
especially if you're not accessing it from another script
it can be for sure
So you're saying I probably won't need to access it?
What type of movement would I use if I want to constantly move a object by a vector
I guess go private until I need it to be public
the vector will be randomly determined at the start of the game
it depends if you need physical collisions and physics simulation or not
I want the object to be destroyed on collision but that is all
You need to use a rigidbody then
ok thanks ๐
code bit too long hold on
Just set the object's velocity at the start and make sure drag is 0
and that's all you need to move it
I cant get my mouse to interact with UI. I changed the default input actions for UI new input system is that why?
- You shouldn't change the default actions, just make your own custom one
- Make sure there's an event system in the scene
- Make sure there's a properly configured input module on the event system
- Make sure there's a graphic raycaster on the canvas
oh mb i couldve tjust tested it
which i did and yeah thats why
okay ill go back to the default one
ty
Hello, for a while now I was trying to use the pixel perfect camera, but encountered an issue when I moved the player. Essentially, when using my Vector3.SmoothDamp camera follow script, my player would shake between pixels when I used upscale render texture/pixel snapping on my pixel perfect camera.
Camera Code:
https://hastebin.com/share/tujukujire.csharp
Player Movement:
https://hastebin.com/share/jiyejavilu.csharp
where the report system at or like support for help
pixel snapping will look really shaky when moving the camera unless you have a high pixel count
_rb.velocity = _currentInputVector * _moveSpeed * Time.fixedDeltaTime;< Velocity should NOT have fixedDeltaTime multiplied into it. THis is basically just dividing your velocity by 50 for NO reason- Your camera script should probably be using
LateUpdatenotUpdate - Make sure your Rigidbody has interpolation enabled
intellisense is beginning to predict my less than family friendly print messages LOL
Fixed everything mentioned, still shaking. Thanks though!
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;
public class asteroidScript : MonoBehaviour
{
private Vector3 direction;
private int maxSpeed;
[SerializeField] private Rigidbody rb;
void Start()
{
direction = new Vector3(Random.Range(-maxSpeed, maxSpeed), Random.Range(-maxSpeed, maxSpeed), Random.Range(-maxSpeed, maxSpeed));
}
private void FixedUpdate()
{
Debug.Log("should be moving");
rb.velocity = direction;
}
}
``` it's possible I am being insane but is this going to cause performace issues if ran 200 times?
Got it, any way to fix/minimize that?
are your rigidbodies dynamic?
I think so
you should check if you are not 100% sure
They are if they are not kinematic
then yes
max speed is 0
you never set it to anything else
and it's private
so you couldn't have set it to anything else
ah yeah, that'll do it lol
high pixel count, or dont use pixel snapping. Most games dont use it. Its a hassle and its okay to have subpixels.
you can also do direction = Random.insideUnitSphere * maxSpeed; instead of that big ugly Vector3 thing
Alright, thanks alot! Probably won't go through the hassle of upscaling all the art.
ok thanks
you probably have an infinite loop in your code
yes do while loop
yes, that loop can never end. just use an if statement like you're doing below
oh ok
thx
remember, loops run to completion. and since nothing inside of that loop can change the value returned by Input.GetKeyUp(KeyCode.S) then it never exits the loop
um how do i close unity when crashed๐
hello friends, I have a question, where can I start to look for FPS tutorials?
oh yeah i got a good youtuber
inb4 brackeys
go search fps builder
FPS games are usually a more intermediate genre. You want to do multiple games before attempting one. Once you've done enough of those games leading up, you wouldn't need an FPS tutorial, you would be able to use docs and piece together small-scope tutorials
the reason why he should search fps builder
where should I start from if I want to end up making a FPS?
start with the basics !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
lets go, thank you! i'll be back
boxfriend
In addition to what Box said. I like to recommend a pure c# course. Also there are resources pinned in this channel.
Catlike coding is great
it doesn't work
that's not specific
Show code
GetKeyUp/Down are only true one frame
that will rotate by 10 degress on the X axis once you release the S key
also keep in mind that for 2d you probably want to be rotating on the Z axis, not the X axis
i'll check this one out first, hadn't heard about it before
yeah but when i released the s key it translated and not rotate
it most certainly rotated by 10 degress on the X axis. but like i pointed out, that's probably not the one you want to rotate around ๐
but how do i repeat it infinitly
GetKey not Up or Down
well GetKeyUp only returns true the first frame you release the key. if you want to check for every frame the key is up use GetKey but just invert the condition (check it is false instead of true)
um i dont know if you guys knew what i meant but i wanted the circle rotate everytime exept when the S key is pressed
Sounds like exactly what Boxfriend said?
Rotate continuously except when s key is pressed?
i dont get it
if (!Input.GetKey(KeyCode.S))
{
//rotate
}
This will rotate constantly EXCEPT when you press s
also make sure to multiply your rotation by deltaTime otherwise it will be zoomin
wdym by not valid
oh nvm
I missed some stuff. I fixed it I think though
and so i use coroutine to make it continue
right?
why? just use Update . . .
but it's in update
and?
Yes. Keep it there
Update runs every frame, which you want
To be clear, Update IS a loop
but when i press S if i want it to move infinitly until the key is up
huh?
Yeah, so do that. In update
so i use loop?
no
Update IS a loop, as I said
just the if statement inside of Update is sufficient
void Update()
{
if (!Input.GetKey(KeyCode.S))
{
//rotate
}
else
{
// move
}
}
Could reverse this of course. I just copied from above cause phone coding sucks
yeah i think i should go to sleep
um do i keep the if statement for the rotate
pls respond
i wanna sleep
just go sleep and come back to it with a fresh mind tomorrow. at this point we have to spoon feed you the answers which is something that nobody really wants to do
๐ญ
I mean, I don't know why you wouldn't.
I literally gave you exactly what to write. But yeah, what box said. Sleep time haha.
I'm making a 2d platformer with a gamepad as input, do people usually use analog left and right movement or a couple of different set speeds (run and walk)
im looking to make a door, and I'm wondering if I should use a rigidbody or what
I am not sure what the best way to rotate it would be, ideally it would stop if it hits something for example
like I could just change the objects rotation, but would it properly push the player and other objects if I did that?
or does it have to be in a specific method? does it have to use a specific method?
Unfortunately
on everything in your world. If your objects move via rigidbody, then yes a door moving via rigidbody should push it. But you have to make sure its rotating with enough force, and not too much to knock some objects out of the world. I found joints pretty useful for this because you can literally make the entire door with no code. It just wont automatically open (or close) depending on how you set the joint constraints. By setting a target rotation, it can automatically try to close at all times for example
If you just directly change the rotation, then it will teleport into objects, and those objects may try to depenetrate themselves (rigidbodies will) but itll be clunky and you may end up on either side of the door by the end.
And if you want it to stop while hitting something, a really light door would technically do this but it may be a bit of fine tuning to make it work properly
well, tbh I'd be ok with other things pushing it but it not pushing other things
I tried to do that but I can only get it to be solid to the player, without the player really pushing it
I think it's beacuse the player doesnt have a rigidbody, just a character controller and a collider
also when its pushing the player it seems to be "choppy" do you know what that is a result of?
idk anything about game physics
character controllers dont respect physics at all, it basically just teleports the player but also makes sure its not stuck inside of anything. So yea the player is not being pushed, your CC is constantly trying to depenetrate which will be buggy
either you need to add a way for objects to push your character controller in a way that looks like physics, or use a rigidbody instead
and yea your player wont push the door because no physics
hm, well I don't want to use a rigidbody because in my experience you basically just cant have tight controls with a rigidbody
you're just at the mercy of chaotic physics simulations
how would I make the door stop if it touches the player, without it pushing the player at all or intersecting them
I tried OnCollisionEnter but it didn't seem to work
wait no
let me fix
nope still doesn't work
@eternal needle
it should just do that by default with rigidbody movement and a collider
hm its set to kinematic is that why
if you just adjust the transform then you gotta do like an overlap check or something
not really sure whats best there
making it non kinematic makes it stop but it jitters when it touches you, depenetrating again maybe?
also, I want to lock the x and z rotation but when I do that it rotates from the center of mass, not the object pivot I set
๐คทโโ๏ธ cant really say much without seeing the setup, or how you're moving it. i cant imagine your previous method of movement was respecting physics if kinematic was toggled
the door is just a box collider and a rigidbody, moving with MoveRotation in FixedUpdate
im gonna watch a video about game physics tho so I know what the foundation of this is
!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.
is there any good documentation somewhere on good practices for persistent data between scenes? I have two scenes I want to be able to move between, and some core data needs to persist, (meta upgrade data for a roguelike effectively, and then on the opposite scene change, currency data that carries from runs back to the hub world)
I've seen things like PlayerPref data, and something about having a master scene that never disables, but I'm not really sure what like...just a good place to start and better understand would be.
You definitely don't want playerprefs or any file read to have persitent data between scenes. That is for persistent data across quitting and restarting.
What you want is to look at DontDestroyOnLoad and additive scene loading
DontDestroyOnLoad is, itself, a scene that will make it so objects are not destroyed when a new scene loads. So you put an object in that scene when you want it to persist
Additive scene loading is very similar, but can do it with prebuilt scenes and it's pretty common to have a scene with UI and manager scripts, then load your location/map/whatever on top
Oh I see, so I could put data managers under that DontDestroyOnLoad part, and I'd be able to call that data from any scene, or similarly with a prebuilt scene as y ou described
Exactly. That way it is all just in memory instead of having to read and write to and from disk
Yes! Just remember, it'll break any direct references from the inspector. So you'll need to use a singleton pattern, or other method to find it and get the settings when you change levels
And be careful not to have more than one
Singleton patterns probably the easiest way to access it and avoid that problem
already using singleton for all my managers thank god ๐
I'm wondering what's the best way to save the position of the player gameobject before a scene change, and teleporting them to the same position when the next scene exits?
- Player clicks on object that triggers scene change. Save his current pstn.
- when the player presses the return key (ESC)/returns to previous scene, load the player position that was saved in 1.
I already have a working scene changer, just need to make sure the player position is saved... or alternatively, the player is teleported to the location of the scene changer object itself when he returns to the previous scene.
Just reference all scene changers in one scene in some kind of manager, save the name/ID/whatever of the last entered scene changer, call the manager in the new scene, search for any scene changer connected with your previous name/ID/whatever and spawn the player at that position
I see, so a singleton manager and a list/dictionary/etc of data containing all scene changers in the game + position?
Then referencing them when the scene change is triggered?
is this a good way to make instance of weapon that im gonna have like 100 of in the future?
A single enum field would be much better than a series of booleans for weapon type.
Also I don't see how this is an "instance" of anything. This appears to be general information for a weapon.
or you could use scriptable objects
i mean create instance of this Scriptable object
no its for each instance of the gunSo. it hsouldd only have one each
as in modes of fire
yeah my english bad
but i think that should be fine
yea. but i also want to make an artifact system using this method. that kind of effect more than just the weapon
artifact? elaborate
stuff like items in binding of isaac that change the game in many aspect like slowdown time. give random enemy debuff and changing player stat
does it still work?
how?
So... do all guns have the same artifacts, or do you have to assign artifacts to each gun individually.
Like, gun A and B both can cause Slow and Blindness, or can Gun A only cause Slow and not Blindness?
the artifact is a seperate thing that player can collect . not apply to weapon
How what?
OK so whats the point
using enumerable field?
An enum
They're not relevant to the gun SO
ah i see the misundderstanding. i thought you say modifying one thing should be fine using alot of bool method like that. i was asking if it okay to use this method on create an artifact system that change many different thing in the game?
Yeah that's fine
But seems a Lil clunky
Might be better to make an artifact and list what it does
In a SO
you cant define custom fuction inside each instance of each artifac, can you?
Does the "get gameobject with tag" work with UI elements ? Such as a panel/canvas
Why not? They're also GameObjects
Note that Canvas is an actual component and Panel is just a cute name for a GameObject with an Image component on it. Either way they're GameObjects
Everything you see in the hierarchy window is a GameObject
@wintry quarry oh i see
another question. should i use switch case to check for what type of shooting or use if statement
You can use everything you want, even a dictionary
i watch enough yandere dev documentary to have paranoid on which method i should you
That's the least of yandevs problems
Switch cases and if statements aren't that far off
In performance
What really fucked him over was his overuse of the Update method and GetComponent spam
Also the fact that mf doesn't seem to know what a script able object is
oh thank god im paranoid on if i should put stuff in update instead of using event or call from another class
Weird, my friend has an issue
Red error: game object null
Edit: i forgt that disabled GO are not detected
(Yes its visual scripting but here it doesnt matter)
whats the better way to getcomponent?
Event if you can
Use it on Awake
And try to use script able objects where you can
Correction, it's FINE to use getcomponent once or twice
i saving Awake for when i need some script to run before start
so get component in start() is fine?
i think this is the wrong place to post this
its cool?
yea
yes
but not every frame
general rule of thumb, update should only contain methods and code that is fairly lightweight
anything that requires lookups should be called selectively or using an event system
got it. thank much for help ๐ซก
is there a more simple way to delay each forloop than using Coroutine?
Seems to me like this should all just be one coroutine
With a delay inside the loop
This is a really weird way to do it, and wasteful too
typical self_effort
For people new to async/await approach,
Let's say we have a method:
public async Task RenameUser(string userId, string newName) { throw new NotRegisteredException(); }
What will the return type look and how can I handle the exception?
Could be a singleton manager with a list serialized in the inspector, just add a "connection" field (name/Id/whatever) to each of your scene changer to know where it goes to/from and the rest is easy
The scene changer itself should have a field for spawn position
Your question makes it sound like a quiz for someone else, are you asking this for your own knowledge?
Usually your own async stuff isnt really needed in unity
Vector3 GetSpawnPos(string cameFrom)
{
foreach(SceneChanger sc in m_sceneChangersList)
{
if (sc.Connection == cameFrom)
return sc.SpawnPos;
}
return Vector3.zero; // Nothing found, check if everything is correct in the scene changers
}```
For my own knowledge, have to abandon coroutines due to the fact that I can't even do basic try/catch inside those in a clean way.
I want to know how exceptions are thrown upwards the stack in cases where I don't want to handle exceptions inside the method.
what does string cameFrom do?
It's the name/Id/whatever from your previously entered SceneChanger
i see
Could be anything you want, just an example
okay i get it now, thanks!
Maybe have a read on the ms docs for async programming
https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/
But I dont really know what you're asking for the exceptions part. Itd be more clear if you share what you're actually doing, maybe then you could even find a way to do it with coroutines. Async stuff really isnt needed at all
The doc also has an example with an async task so you can see what goes inside the method
Okay, so to confirm, what I can do is either:
try { await task(); } catch { //handle exception }
or
task().ContinueWith(task => { If (task.IsFaulted) { //handle exception } });
Right?
I haven't really used that 2nd method at all so
I guess, and the first one is what the other person in the other channel told you.
yep, thank you!
you won't get a clean try-catching in async/await, instead it will be much worse
many ways to check if a task was completed or was cancelled. as I've written in other channel, you can do .Result or try-catch it's CancelledOperationException exception
you don't want that ContinueWith in Unity when running it via Task.Run just a heads up
instead you'd want to make your own dispatcher
Don't agree, here is why (but feel free to correct me):
How can I handle an exception outside the coroutine?
How can I preserve the exception stack? (e.g. I did StartCoroutine(_DoStuff(null)), but _DoStuff() isn't supposed to receive null, so it throws NullPointerException().
How would you know who sent null? Coroutines erase the call stack, which is horrible in production, as you can't trace the error source.
I am using moveposition for movement and using transform.position for keeping player in bounds. It is causing glitches as the player will get stuck in bound position. IS there an easy fix or do I need to change the transform.position to moveposition for keeping player in bounds
You should not be mixing Rigidbody motion and Transform motion.
Beyond that, if this is 3D, MovePosition ALSO doesn't respect collisions.
The real robust way to do this is move with velocity and use Colliders to make your bounds
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletMove : MonoBehaviour
{
public float bulletSpeed;
private Vector3 newPos;
private Vector3 originalPos;
void Update()
{
originalPos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
transform.position += transform.forward * Time.deltaTime * bulletSpeed;
newPos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
CheckForCollision();
}
void CheckForCollision()
{
float distance = (newPos - originalPos).magnitude;
Ray ray = new Ray(transform.position, -transform.forward);
RaycastHit hit;
Physics.Raycast(ray, out hit, distance);
if(hit.collider != null)
{
Debug.Log(hit.collider.gameObject.name);
Destroy(gameObject);
}
}
}
is this the most efficient way of fast bullet travel detection?
ok
Raycasts are not going to work properly in Update if the things they're supposed to hit are moving. Collider positions don't update until the physics update phase. Physics things belong in FixedUpdate
i heard rigid bodies dont detect collisions if the bullet is too fast though
is there any other approach
Rigidbodies with continuous collision detection should be pretty good. Worst case you add raycasting like you have here but it should be in FixedUpdate with Rigidbody doing the movement
tghank you
BTW your whole newPos = new Vector3(...); etc lines are super verbose and inefficient. You can just do newPos = transform.position;
for some reason i thought the position would update so i tried putting it in a new vector 3
can i just do it for both?
Vectors are value types, not references.
Yes you can do it for both, but really it won't be necessary to even have these fields when moving with a Rigidbody
yeah i deleted them now but i just wanted to know for future reference
thanks again
ill play around with the rigid body instead
pls help me i downloaded unity but it dont downloaded visual studio 2022 if i open an skript i get to visual studio code
Don't crosspost
how do I find the gameobject hosting my script?
gameObject
that is not what I wrote
well if thats the case lemme go write what you wrote
do you not know that C# is case sensitive?
If you just want the Transform you can leave out gameObject entirely
btw you dont even need gameObject in this case. transform.position does the same thing.
Time to go and learn Unity I think
Just transform
hello I have this issue in my code : Assets_Script\PlanePhysique.cs(53,22): error CS0266: Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?) but I dont see were there is a "double" in my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class PlanePhysique : MonoBehaviour
{
//constante
private float g = 9.81f; //pesenteur
// constante air
private float Mair = 0.029f; //Masse molaire air
private float R = 287.0f; // constante des gaz pour l'air sec en J/kg.K
private float pAir = 0f; // Masse Volumique de l'air
private float L = 0.0065f; // gradient de tempรฉrature standard de l'atmosphรจre en K/m
//condition de vol
public float Tempรฉrature = 0f; // tempรฉrature en degrรฉ Celsius
private float TempรฉratureKelvin = 0f; //tempรฉrature en Kelvin
public float PressionAtmosphรฉriqueNiveauMer = 101325f; //pression atmosphรฉrique en Pa
private float DensitรฉAir = 0f;
//Position avion
private float Altitude = 0f; // Altitude de l'avion
void Start()
{
TempรฉratureKelvin = Tempรฉrature + 273.15f; // calculรฉ la tempรฉrature en Kelvin
MasseVolumiqueAir();
}
void FixedUpdate()
{
//rรฉcupรฉrer les valeurs du joystick
float xAxis = Input.GetAxis("Horizontal");
float yAxis = Input.GetAxis("Vertical");
Altitude = transform.position.y;
}
void MasseVolumiqueAir()
{
pAir = PressionAtmosphรฉriqueNiveauMer / (R * TempรฉratureKelvin); // calcule la Masse volumique de l'air
Debug.Log(pAir);
}
void CalculDensitรฉAir()
{
DensitรฉAir = pAir * Math.Pow((1f - (L * Altitude) / TempรฉratureKelvin),g/(R*L)); // <-- THE LINE WITH THE PROBLEM
}
}
You want Mathf.Pow, not Math.Pow
Math.Pow returns a double
ah ok thx
https://gdl.space/xeraqavifa.cs how do I improve the performance of this?
I'm not sure how to make distance a vector and then use the vector for less if statments but I am sure it's possible
For one, cache the transform.position calls in variables
You're accessing it like 20 times
Making copies every time
Just do it once
oh shoot
Also why do separate xyz distances?
I'm not sure how I am supposed to only chance the one axis and how to find out if they are greater or less than stuff using a vector3
You could just do something like
asteroid.transform.position = Vector3.MoveTowards(player.transform.position, asteroid.transform.position, maxDistance);```
This would replace all of your Update code
oh stepping by maxdistance is genius, I don't want the asteroid to move the player tho,
Nothing in there will move the player
A secondary issue here is Rigidbody motion isn't going to play too nicely with this Transform motion.
let me try this first
Wait is this supposed to wrap around
Like asteroids
Because my code is just limiting the distance, I think I misinterpreted a little ๐
yes, it's supposed to wrap around
it works now just when rendering like 15 there are some issues
30*
Are you sure this code is the issue? Have you profiled it?
If so, then try reducing the number of copies you're making of the positions like I mentioned above.
More caching. More local variables.
ok, I removed all of the transform and all variables are private, I changed the number from 30 to 15 but the fps is still 5
like an unwavering exact 5 it's strange
You need to use the profiler
Otherwise how do you know this code is even the issue?
yea fair I'll figure that thing out thanks
ookay this is gonna be more difficult to understand than I thought
Yes cursed
how to uncursed?
I don't even understand what you are trying to do
random point distribution
Use weighted selection algorithm, which is what you're sort of doing here but in a cursed way
thank. will look into it
Does exist a way to lerp via code the Weight or the Vignette Intensity of a Global Volume?
Weight field is on the Volume component too
I wonder if its possible to do it by using Leantween
So far I found a way to suddenly do it
now I need an interpolation
Interpolation is always the same
true
I usually achieve that with Leantween.value since is visually simple and has lots of parameter to play with
but for now it doesnt seem working
why would you use fixed update apart from physics?
For anything that you want to be consistent regardless of framerate. deltaTime can only accurately adjust for framerate discrepancies for constant/linear changes over time. Anything with second order changes over time (acceleration, growth of gaining money/points, ticks in a simulation game) requires a fixed time interval for deterministic simulations.
and why is fixed update associated with physics?
For exactly the reason i just described
To give a consistent, repeatable simulation in the presence of second order changes over time (for example acceleration due to gravity or any other forces)
second order you mean x^2 for example?
d/dt^2
In this case m/s^2 but sure
https://streamable.com/u7y2ia knows when the second tab is active, the game freezes. How to turn it off
https://discussions.unity.com/t/how-do-you-keep-your-game-running-even-when-you-switch-out-of-it/928
Whenever I run my game in unity or build a standalone, it works fine. When I alt-tab out of it or switch to another program, the program stops going and then continues right where I left off when I come back to it. I want the game to continue running while I am switched out. Is this possible? The reason I want to do this is that I'm making a...
Thank you
sorry, I dont understand second order
you dont mean to the power of 2, do you?
And I dont understand the "tick" system in Unity
if anyone could explain
do you know what is differentiation?
not really
what is icon type? can i use it to like assign icon to my item?
or i just use image type for it
or sprite.... idk anymore
im new and kinda wanna try making something anyone got ideas
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
no i know how to code ( a lil)
also i dont wanna learn mobile and vr
I''m trying this approach, guess I have to interpolate the 3rd parameter, how can do it?
learn is not just about coding although it will teach you how to code with Unity. Nobody forces you to learn mobile or VR although there is very little difference when using Unity
ok
I really hate to use Update space or even a whole coroutine just for that, I need to somehow do it with leantween
the thing is, even if tween the T, do I need to call this Interp function everyframe?
The whole point of the tween library is to not have to do anything in Update or a coroutine
IDK if leantween has support for custom tweens. DOTween does
i realized i can just put many scripable class inside on script so i delete all
SO script and put it into one SO script
now i got this error
You can't do this, no.
Filename has to match class name
So one file per class
Not sure why you'd want to do that anyway
look clean
I'd actually would pack a bunch of SOs together if I could
We have different definitions of clean

You actually can do that if you use an assembly, tho that's a huge pain to setup
At the end I achieved the tween with this code, even if I think it can be done in a clear way
should i use list or enum to hold a list of scriptable object?
Iirc you can also manually add components using AddComponent(typeof(SomeComponent)) but I don't know if that works in editor
A list
Why an enum?
why not?
I understand why it doesn't work with the editor, but I could easily see it working with an attribute to define the SO
how would an Enum hold a List of SO's?
ah isee
but until then I'll stick to serialize references
Also I know JsonUtility isn't that great but can it serialize tupples ?
no
It uses the same serialization as the rest of Unity
also i would like to take a deep appriciation to this chat that help me alot.the big part that i like about this is the rule is not so strict that only question and answer can be send here or by god using "threat" for question.
as a person with extreme social anxiety asking for help through a thread feel very isolated
(I don't really know if this is the right channel to use :'D)
Hello, I'm really new to coding and overall game making, and i have this reoccurring problem with my game (I'm making Snake for a school project):
Every time that I build my game there is this problem when I move to a second scene (I have main menu and scene for playing) it all turns black, but it only looks like that if I use another computer, on mine it's all fine.
Is this maybe something that other's struggled with/a common problem? I haven't found any information about it online.
All that there is, is just the player, snake's segments, score, sound and pause menu (when u click Escape).
I can add all the information needed!
(I attached the photos for how the game looks like for me, and for another player on another computer).
hello!
i have a gameobject that creates a gameobject but not as a child(and i want to keep it that way).
i want the created gameobject to follow the gameobject that created it. is there a way to reference in script the "creator" gameobject?
show the script that changes scenes
here
how do i instantiate smth between 2 points
so it would be a random spot inbetween those points
Random.Range
show the scripts associated with the backgroud gameobject
3D points?
2d
Instantiate(enemyPrefab, new Vector3(Random.Range(spawnPoint1.x, spawnPoint2.x), Random.Range(spawnPoint1.y, spawnPoint2.y), 0), Quaternion.identity);
thats what i have so far but it has some errors
[SerializeField] private GameObject enemyPrefab;
[SerializeField] private float numberofenemies;
[SerializeField] private Transform spawnPoint1;
[SerializeField] private Transform spawnPoint2;
those are my variables
show the console log
Severity Code Description Project File Line Suppression State
Error CS1061 'Transform' does not contain a definition for 'x' and no accessible extension method 'x' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\vinny\Shadow Brawl\Assets\Scripts\EnemySpawner2.cs 22 Active
I don't have any scripts associated with it, it's just a plain object?
ex: spawnPoint1.position.x
are you moving the sprite from any scripts?
try making it a prefab
I'm sorry I don't really understand what i have to do 
What are Prefabs in Unity? In this video you will find out everything you need to know!
More on prefab workflows: https://docs.unity3d.com/Manual/Prefabs.html
Join the community โก๏ธ https://www.yetilearn.io/
In this tutorial, we'll be showing you how to create and use prefabs in Unity. Prefabs are a powerful feature of Unity that allow you to ...
drag the "background and pause menu" like he does with the cube
or just the background photo
try and see what works
okay Imma try it, thank you
can soemone help me with this?
void Update()
{
for(int i = 0; i < numberofenemies; i++)
{
SpawnEnemy();
}
}
private void SpawnEnemy()
{
Instantiate(enemyPrefab, new Vector3(Random.Range(spawnPoint1.position.x, spawnPoint2.position.x), Random.Range(spawnPoint1.position.y, spawnPoint2.position.y), 0), Quaternion.identity);
}
so this should work right
You can pass the reference when you create the object. https://unity.huh.how/references/simple-dependency-injection
it will spawn numberofenemies every frame
oh wait yeah lol
but that should spawn numberofenemies
i never have been good with for loops
do you want it to spawn them simultaneously?