#💻┃code-beginner
1 messages · Page 119 of 1
and you wont get shot from smth you cant see
also whats the best way to keep track of when all the enemies die
something like this will work?
var obj = Instantiate(...);
obj.creator = transform;
See the step 3, you don't want to expose via public vars it defeats the purpose
use a public count variable which is equal to numberofenemies in an empty gameobject then extract 1 everytime an enemy dies
why does it look like this?
so have this in my enemeies death function
EnemySpawner2 enemySpawner = FindObjectOfType<EnemySpawner2>();
enemySpawner.remainingenemies--;
is it meant to be like this?
This will create random instantiation coordinates in a rectangle between the two of them as well.
Get the middle point and if you need to randomize it use https://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html to variate around it
yeah its good
nvm i solved the problem
well the y will be the same
yes
it has to set the RenderCamera with the Main Camera right?
variation there will sometimes create coordinates right on top of one of them as well
yeah but it will be a low chance since its a pretty big area
what about this:
var obj = Instantiate(...);
obj.GetComponent<objScript>().Initialize(transform);
and in the obj script:
private Transform creatorTr;
public void Initialize(Transform tr)
{
creatorTr = tr;
}
When instantiating you get a reference from it, you don't need to get component again
Also if your Initialize return the object you can inline it as well.
public ObjScript Initialize(Transform tr)
{
creatorTr = tr;
return this
}```
Then var obj = Instantiate(...).Initialize(transform);
And class name should be capitalized too to not create confusion
this a good way of spawning them when you go through that
this is my Scriptable Object. can i make so that i can set Teir_Value any type and value in the editor?
it should work already no?
this will just delete the gameobject this script is attached to after a frame, right?
pretty much
i mean the item in enum sometime is int and sometime is float
nvm i can just use float
Hi. I want to make a zoom change through a script. How to access the zoom change in the screen through a script (what is the name of this thing). I tried to find it on the Internet, but I didn't find it.
why? this is editor only..
Ok. Thanks
hey so quick question so i have a variable that gets increased by 1 when a enemy spawns and decreases by 1 when a enemy dies that way i can keep track of when all the enemies are dead but if i just check if it is 0 then it will fire before the enemies spawn how can i fix this
are you using Update loop?
I guess you could add another check that would prevent the code from firing for some time while the enemies spawn
hey guys im jw cos im new to 2d unity what would be the best way to make an infinite flappy bird game?
like im talking about generating new chunks of the level
ik how to implement the actual gameplay
yeah
void Update()
{
if (remainingenemies == 0f)
{
NoEnemiesLeft();
}
}
why not just use An event when something happens. Eg enemies Updated like Removed or Add
no need for Update loop here
guys does somebody know EXACTLY why is FixedUpdate related to Physics
because thats what unity made it for
but why essentially?
It's a method that allows to run the code in step with physics calculations
what do you mean by in step
consistency of physics
on the same frame
If you're moving rigidbody on Update for example , you're mooving it outside of its intended physics loop and you get weird sync issues , innacuracy more
ok, i think im getting it but I still need help at understanding whatis THE PHYSICS LOOP
I already read that and still dont understand
then idk 🤷♂️
Anyone good at photon / parrelsync that can help me by any chance?
I mean, the thing is, Physics Loop is independent of any method in our script?
it is just something that exists?
our scripts only call to the engine apis, the physics update is already running regardless of our inputs/scripts
hm, I need to instantiate game objects that immediately delete themselves after one frame, but I can't just copy an existing gameobject since it would delete itself- how could I do this?
You can also use coroutines to run on fixedUpdate frames
'Tick' isnt used that much in unity context but usually it means one physics frame (or rendered frame)
If your physics is set to run 50 times per second (default) then you could aay that the tickrate is 50
i dont understand teh concept of physics "running"
If object is falling, its fall processed every physics frame. It is different from Update frames in that FixedUpdate will guarantee fixed amount of frames to run, they could be late, in that case it will try to hurry them up later, but they will run. Update doesn't care how much frames it will run, and runs as fast as it can.
is it possible to add a component to an instantiated object
okay. Maybe Im asking a really dumb question
but what exactly is a frame
addcomponent, it returns the newly added component
This is a frame https://docs.unity3d.com/Manual/ExecutionOrder.html
All that happens during a frame.
so why are there update frames and physics frames
because Update is needed to run something every frame
or we would have to make our own ticks
for every object
To ensure stable physics simulation even if your framerate is bad/not stable
alright Im really confused
Everything you do to the instantiated object will happen on that frame when you create it. It will only be deleted the next frame.
The Fixed in FixedUpdate means that it runs a fixed amount of times per second, regardless of your rendering speed
yes thats what I want to do
what is the point of that? also that expensive
you should at least pool them
yeah, thats what i understand but I dont get why we talk about physics frames and logic frames
I just tried to explain that
I want to create an explosion radius, that only exists for a frame to check if something is inside of it
goctha.. You should still cache it then and just disable/enable the same one
Instantiating and destroying makes a lot of garbage
And I appreciate it but I still dont know
i mean
You could just use one of the Physics.Overlap methods
No need to create an object for it
is fixed update called before update?
you literally were sent the link twice
yes man I know
it tells you exactly the order..
oh that works
thanks
https://docs.unity3d.com/Manual/TimeFrameManagement.html
read (Fixed Timestep)
At the start of the each frame, Unity performs as many fixed updates as necessary to catch up with the current time.
etc..
Yes but only if it needs to. So only if fixedDeltaTime amount of seconds passed since the last fixedupdate
ok thanks for all I guess
It can run twice or more too if your framerate is less than the fixed delta time/physics timestep
actually whether update or fixed update runs first doesnt matter, you can have multiple or none fixed update in one update cycle (also for long run game you cant tell which one run "first", since there is no such concept)
But if fixedUpdate is the only way to acces the Physics calculations, how is it possible to calculate that stuff inn Update as well
Im really lost please help
In some cases you can tell that fixedupdate runs first. Like when reading GetKey. If you cache the GetKey in Update and use it in the next FixedUpdate, you will get 1 frame delay on that input, but if you read it directly in FixedUpdate then it is up to date
hello!
if i call ontriggerenter function in antoher function it will just run the function as if it was a normal function?
A bit confusing and Im not great st explaining it 😅
make a method they both can call
eg move the suff from OnTrigger to another method
then only call method
private void OnTriggerEnter(Collider other)
{
//some code
//some code
//bad
//instead do
Method();
}
public void Method()
{
//code
//code
}```
now you only need call method
It would but it's very awkward
OnTrigger is a special unity method let it be lol
if you're manually calling it something is flawed in your design
hm- right, another problem I have is that I need to change a value on any gameobject within the "explosion" (i.e decrease health)
Hi. I need to find out: Did I access the "speed" variable correctly, which is in another script? It's just that when I launch it, speedFire does not change in any way, unlike speed.
i have 2 gameobjects with 2 different boxcolliders and i want to call the first trigger function from the second gameobject.
which could be done by spawning an object, not as much with the physics2D.OverlapCircle
( I think, i am probably wrong )
if they are child of rigidbody it should get called if either touches something no?
like if the second bject is triggered the first to act as if it was triggered
oh..
It gives you an array of colliders
You can loop over them and do whatever you want
btw they both get the trigger/collision messages
so idk why it would be a big deal to put script on other object if thats what does logic
actually update call is still the most suitable place to call any GetKey since fixed update (you can still call it in fixed update) can still miss the rising edge to stable event transition
key event has four states: idle (getkey==false) rising edge (getKeydown==true) stable (getkey==true) falling edge (getkeyup==true) (clock indeed....), all transitions of state are happening on update so fixed update can miss
lets say if the transition from rising edge to stable happening on t=0.0048s (at 3rd update frame) and you check it in 2nd fixed update frame (0.040), you miss it
bc i want the first object to ignore the second object's trigger if it is triggered by the wrong object
yeah, but I am not sure how I can have the script doing the explosion tell the gameobjects caught within it to decrease their health
bc if i make it a child it will never know if the trigger was called by itself or by the child
You can TryGetComponent the health script from the collider for example. Or GetComponentInParent
oh right, that
Hi. I wanted to make the variable "speedFire" depend on a variable from another variable "speed" in another script. I wrote this line, but after starting the game, the speedFire value is set to 0, and the speed value changes. What's wrong?
no doubt speed is a value type
Does speed change after you set speedFire
speed and speedFire have the data type: float
so value types. This is basic C# knowledge you should already have. the difference between values type and reference types
you should cache the reference and make a property
public PlayerController player;
public float Speed => player.moveSpeed;
if you want to link them easy
Are you changing speed after changing speedFire
Speed doesn't "track" changes. You set the variable to whatever speed was when that line of code ran
You shouldn't have a speedFire variable at all if you want it to track, just use speed (after you cache that getComponent call into a variable you can reuse)
Too smart for me. I'll figure it out later. Thanks
ffs guys, I'm trying to get him to understand WHY this is so
Oh, thanks. Now I kind of get it
So am I, just not using the words "value type" and instead explaining what that means
The concept is more important than the terminology
except the terminology is how you find the right docs
where is it called from?
hey can i export an indivitual sprite to a png file?
from unity you cant with built in tools
Hello,
can someone help me.
I can't change the color in the fbx that I'm trying to edit here.
how come?
you can open the atlas and cut the sprite you need into a new file, with any graphics program
you need to create new material and assign it to the model
what you have selected is not the mesh itself
its an empty root object
which has several meshes under it
each will need a material assigned
you can also do this through the imported object ui
click on the fbx in projects panel and find materials tab
and this is a coding channel
do you have to convert color to color32 or do they work interconnectedly
can I assign a color value to a color32 variable?
you dont have to convert they can be used interchangeable
unity already does it for you
alright thank you
Color32 should be faster afaik, so use that when possible
only 4 bytes (color32)
floats (color) are 4 bytes each channel
How to use smoothDamp() to move smooth to a given coordinate over a period of time through a coroutine?
chatGPT believes that the smoothTime parameter is the time it takes to arrive, but that doesn't seem to be true.
public void OnClick(InputAction.CallbackContext context)
{
if (!context.performed) return;
var device = playerInput.GetDevice<Pointer>();
bool hitUI = IsRaycastHittingUIObject(device.position.ReadValue());
Debug.Log("Did we hit UI? " + hitUI); // Always true
if (device != null && IsRaycastHittingUIObject(device.position.ReadValue())) return;
LeftClick();
}
private bool IsRaycastHittingUIObject(Vector2 position)
{
if (_PointerData == null)
_PointerData = new PointerEventData(EventSystem.current);
_PointerData.position = position;
EventSystem.current.RaycastAll(_PointerData, _RaycastResults);
return _RaycastResults.Count > 0;
}
did youDebug the raycasts results ?
When clicking on ground
When clicking on GUI
So it is hitting the camera??
When I hit an object:
I never seen this through inspector hmm I assume because camera has that physicsraycaster that sends info
I use Odin
public List<RaycastResult> _RaycastResults = new List<RaycastResult>();
My instinct says to check for intances of Graphic raycaster
thoseare what start the ray on canvas no ?
I actually never looked into it so I can't say for sure
im having issues with some other UI related stuff lol
Do you know how to check for module graphic raycaster in the result?
if (isThrowing)
{
lr.enabled = true;
DrawTrajectory();
ThrowProgress++;
print("tp: " + ThrowProgress);
return;
}
I have this code where throwprogress is basically the force that the player throws at. I had this in fixedupdate but the trajectory line was really laggy, but now that i put it in update the throw force is increasing too quicckly, how do i fix this?
In _RaycastResults
not sure
something very wrong if its showing that though
I think there is Blocking Objects option on raycaster
nvm thats for colliders
how were you moving the box in fixedupdate
oh the line nvm
use Time.deltaTime if you want consitency in update
wait what is throw force? the line ?
throwprogress is a number that is clamped to 100
so its like
100% * a force that is defined elsewhere
public void RaycastAll(PointerEventData eventData, List<RaycastResult> raycastResults)
No options
show how you move the box
oh nvm
this is just the force for the box to be thrown
yeah
okay, thanks
No
"// Can't use IsPointerOverGameObject() from within InputAction callbacks as the UI won't update
// until after input processing is complete. So, need to explicitly raycast here."
does someone knows why SmoothDamp() takes too much time?
I set smoothtime parameter at 0.461 and the result take 2+ seconds although I had break codes which defences float issues
IEnumerator IntroMove(Vector3 target, float time)
{
Vector3 Start = transform.position;
doesMoveCoroutineEnd = false;
destinationX = target.x;
destinationY = target.y;
Vector3 velocity = Vector3.zero;
//Debug.Log(Vector3.Distance(transform.position, target));
float deltaTime = 0f;
if (!doesMoveCoroutineEnd)
{
while (Vector3.Distance(transform.position, target) > 0.01)
{
deltaTime += Time.deltaTime;
Debug.Log(deltaTime);
this.transform.position = Vector3.SmoothDamp(this.transform.position, target, ref velocity, time);
// if (deltaTime > time + 0.1f)
// {
// Debug.Log("bruh");
// transform.position = target;
// doesMoveCoroutineEnd = true;
// yield break;
// }
yield return null;
}
}
transform.position = target;
// Debug.Log("------------Task End------------");
doesMoveCoroutineEnd = true;
}```
this is the last log of IntroMove
IEnumerator CaneGunFire(int FireNoteIndex, Vector3 loaction)
{
...
timeLeft = player.noteEndMS[FireNoteIndex + 1] - (player.CONSTANT_TIME * 1000);
timeLeft = Mathf.Round((float)timeLeft) / 1000;
Debug.Log(timeLeft);
//yield return StartCoroutine(SmoothMove(new Vector3(transform.position.x + 8, transform.position.y, 0), (float)timeLeft));
yield return StartCoroutine(IntroMove(new Vector3(transform.position.x + 8, transform.position.y, 0), (float)timeLeft));
...
}```
this is timeleft
so actually I excepted SmoothDamp IntroMove will end near 0.461 seconds, but the result is 2.07 seconds
How to solve this problem?
wait for me
hey so i have 3 different enemies each has a different controller script which also deals with health and stuff how do i have them take damage
these timeLeft = player.noteEndMS[FireNoteIndex + 1] - (player.CONSTANT_TIME * 1000); are the values I wanted to see
wait
and it is just converting ms to second I remember
Debug.Log("TimeLeft = " + player.noteEndMS[FireNoteIndex + 1] + " - " + (player.CONSTANT_TIME * 1000));
Debug.Log(Mathf.Round((float)(player.noteEndMS[FireNoteIndex + 1] - (player.CONSTANT_TIME * 1000))));
timeLeft = player.noteEndMS[FireNoteIndex + 1] - (player.CONSTANT_TIME * 1000);
wait, you should be reducing time by deltaTime every itteration of the loop
here
this.transform.position = Vector3.SmoothDamp(this.transform.position, target, ref velocity, time);
you are using time as a constant
oh
Hi. I have a problem: I wanted to do all the sound activation in 1 script (to make it easier and everything in 1 place), I kind of did everything right, but when I start the game, for some reason all the sounds are activated immediately, and they stay that way forever (even though all the objects on which they depend are turned off). What did I do wrong?
I just remembered this thing runs in coroutine
💀
wait I'll try
uh so should I rewrite like this?
this.transform.position = Vector3.SmoothDamp(this.transform.position, target, ref velocity, time-deltaTime);
which is the time left for end
yes
how could i know when sombody closes the app?
which platform?
android
OnFocus
alright thx
dont do stuff like GetComponent, in update
also disable PlayOnAwake on AudioSource
I have some pretty basic code here, but i can't seem to manipulate anything in the nodes[] list. Does anyone know why? https://gdl.space/pefomeduxu.cpp
And in which void should I do it?
Or do I need to create a separate void for each object?
because you only access node zero
well yeah, but node zero doesn't move either
void just a return type for a Method, they're not called voids lol
Ok. Thanks
and you should Set it in inspector
i have a question about scriptable objects
when using scriptable objects should you add values that can change to them or should every value be fixed but accessible, im having an issue with my item scriptable objects, basically im changing the amount of the item but it changes the whole scriptable object for every item
how are you supposed to handle values that change inside of a scriptable object?
short answer, don't
so whats the right way to handle the amount the correct way
seperate serializable class
so just an object with the item scriptable object + amount
yes, per instance of the objects using the SO
you can create an instance of the SO for each object, which will allow them to update their own values, but then you still need a way to serialize and save/load it at runtime
is it possible to set the variables in the SO to public get, private set so i can avoid doing it by mistake?
ofc
yes if you use [field:SerializeField]. they are called Properties btw
field:serializefield
although why anyone would write code 'by mistake' is beyond me
What version of unity do i need to use to not pay the actrivity fee
any current version
hey so im struggaling with damage here is my takedamage function
public void TakeDamage(float damage)
{
currentHealth -= damage;
if (currentHealth <= 0)
{
Die();
}
}
how exactly would i pass the damage i want to deal from another function
oh so they removed it
TakeDamage(Damage);
would it be like this
no
Then how come i dont need to pay
because, if you bothered to do any research, you would know that it starts with Unity version 6
Chill
then don't be lazy
😉
I wouldn't worry about it anyway, you think you will have a million dollars revenue and million downloads ?
rofl
You think so, thanks
I'm if you're making that kind of cash the last thing i'd worry about is the 2.5%
OKay thanks
Another one who's bought the mansion in Malibu and the Ferrari even before they've started to design their game
Yes its already on the way 🙂
Ain't gonna happen kid
ohhh thats sad
Fact of life, sorry, the truth hurts
so would it be like this??
use interfaces
or just look for this class specifically
then pass the value in the method as you did any other methods you used..
😎
in Visual Studio 2019 can I change the color of variables ? or give a special colors to all "Unity" related methods
this is literally something you should try before asking here
well it doesnt seem to work weridly
feels to white
define "doesn't work"
why are you using 2019
and yeah ofc you can change everything
default one, 2022 takes ages to update for some reasons
so OnTriggerEnter in contrast to Oncollision checks if the check mark in clicked but it is still a collision detector?
Triggers are no collisions
does 2022 changes colors ?
You can change those colos in the Text Editor section in both
any tips reagrding where ?
i cant find any panel or settings regarding Unity tools in VS
but their both used for detecting collisions no
Tools > Options > Fonts and Color
Tools->Options->Environment->Fonts and Colors
ty guy
No
Triggers detect Collider in Trigger
they're not collisions
Collisions are solid
doesnt looke like there is a way to customize Unity stuff
yeah that sounds right i was just wording it wrong
Hello again. I have a problem with the character, or rather with the speed. In my script, there is activation by the keys: "C" and "LeftControl". because of the 61 lines, the 40 line does not work. (when I press C), the speed remains 10. I understand why this is so (because the shift is not clamped, and therefore the speed is 10). How to fix it?
dont ever use == with floats first off
they're usually slightly imprecise and never exactly the value you want
you should not check controller height for speed
rather make a crouched boolean
you press the key once it hits the else right after so not sure what ur doing there. can you explain more what you're trying to do?
use "<=" and ">="?
Ok. Thanks
what are you trying to accomplish cause I see a few flaws here . esp Timespeed doesn't have a time.deltaTime you will get all sorts of weird results
your decrease will happen fast if you have high FramesPerSecond
also once it hit 0 it never gets put to 0 or a bool to stop so it will keep decrease
So that's the problem: at low FPS it is spent slowly, and at high FPS it is spent quickly. Thanks again. I was wondering what the problem was.
The heavens have shined upon to me, for by nothing short of a miracle, my code worked first try.
Hi,
I have a base class named FS_Unit which stands for File System Unit, and have 2 derived classes File and Directory.
I want to make File and Directory scripable objects, while also making them inherit from FS_Unit class. I cannot inherit from both FS_Unit and ScriptableObject.
What can I do?
how do i stop all other animations for a character
you can only inherit from one class per class
you could make it so directory inherits from file and fs unit inherits from directory
then again, I wouldnt be able to make Directory into a scriptable object because it inherits from File already
Basically, is there a way to create an object into a scriptable object when it already inherits for a class?
animator.Stop() ?
wdym
easiest way, if all your classes are serializable, make an SO with a Directory variable
StopPlayback???
Ah that works, thanks!
does it work ?
I wanna make a 3D enemy movement script that just flies directly towards the player but cannot turn quickly meaning if you dodge it will miss
is there a good tutorial, most 3D tutorials are more like a top down game displayed as 2d
I guess I could get the rotation from the front of the enemy to the player then marginally change the rotation
yeah I just misremembered should be that one
hello!
is there an equivalent in c# for c++ pair<T,T> ?
besides tuple
anyone know why i have it set a bool to true but it just keeps repeating the first frame of the animation
instead of asking there
i want it to play the animation and hold the last frame
How do I find out how much rotation is need for one object to face another?
just stays like this lol im assuming smth is wrong with my code but not sure how i would fix it
private void Die()
{
if (enemyController != null)
{
enemyController.IsStunned = true;
}
if (enemyController2 != null)
{
enemyController2.IsStunned = true;
}
if (enemyController3 != null)
{
enemyController3.IsStunned = true;
}
animator.StopPlayback();
animator.SetBool("Dead", true);
StartCoroutine(Destroy());
//Destroy(gameObject, 3f);
}
this is the die function
whats the opposite of ignore collision
Physics.IgnoreCollision(GetComponentInParent<CharacterController>(), itemdrop.gameObject.GetComponent<Collider>());
Consider using the third parameter https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
Why doesn't the "public GameObject island" appear as a variable in the controller when I have added the script to it?
oh okay, is ignore true by default then
Take a look at the example. The method returns the degrees between 1 vector and another vector ahttps://docs.unity3d.com/ScriptReference/Vector3.SignedAngle.html
Are there any errors?
check your console for errors
thanks, I'm gonna give rotate towards a shot as well
nothing comes out
nothing comes out
Are you using a custom inspector?
if I click on the script, the GameObject is there.
no, I have just created the project
screenshot console
how do you just move something 3f forward regardless of direction
like it can face in any direction but I want it to move "forward"
For example Quaternion.FromToRotation or Quaternion.Angle depending on what you really need
Or Quaternion.Inverse and multiplication
I didn't touch anything in Unity, I just created an empty GameObject and created the script, then dragged the script onto the gamenObjecy called Controller.
I didn't touch anything in Unity, I just created an empty GameObject and created the script, then dragged the script onto the gamenObjecy called Controller.
Forward relative to the world or relative to itself?
Sounds like you just want Vector3.forward
The only thing I can think of is Domain Reload is disabled, try closing the project and opening it again
okey
yea I used the moveforward velocity rb thing
does not work😢
what Unity version?
anyone know for this??
2022.3.16f1
odd, sorry I'm out of ideas, this all looks fine
From what state do you transition to this one?
any state
I figured so
Any state includes that Enemy1_dead state as well
Theres an option "can transition to self' in the transition I think
Uncheck that
try resetting the component
or reimport the script
it seems to now not even trigger it
nothing happens
no problem, thanks for the help
u tried this too?
yes
📃 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.
yes, in all scripts
in all projects or only this one?
I need help on something, where should I write?
just say what you need help on
Have the animator open next to the game view when playing, this way you can see what's going on.
You probably have some other transition that is triggering too
do you ever call IsPressed() ?
what do you mean?
Depends on what you need help with of course. #🔎┃find-a-channel
!support
Take a look at #🔎┃find-a-channel
:warning: This is not a channel for official support.
Please do not ping admins, moderators, or staff with Unity issues.
oh yeah i do
per button
all teh other things in the scripts are working
just not the particles
yes
I want to make a map based game (strategy similar to hoi4) I have maps ready but I don't know how to do it (I followed the guides but I don't know how to use it). If you have any advice, I would be very grateful, sir.
i think its because you never stop the particle systems
also when playing or starting them check if they are alerady playing.
okay
something like this:
if(!particlesyst.isPlaying) particlesyst.Play();
if(particlesyst.isPlaying) particlesyst.Stop();
if you never coded before this will not be easy at all
start with a more basic game
game jam scripts are some of the grossest stuff I've ever written
how do I make a object spawn randomly inside a sphere but also not too close to the center?
like 2d platform ?
pixel game ?
yes
The problem is that the particals only starts when im in the scene view
sure anything that can build you up
thanks
if you plan on doing strategy go though you might want to look into many of those patterns
wdym not too close?
u want it to spawn on the sphere or inside?
okey
Random.insideUnitSphere
still not working
This might be a really stupid question but why am I unable to attach a script with generics onto a game object. It extends MonoBehavior
show script
because cannot resolve the generic in the inspector
public class Projectile <T> : MonoBehaviour where T : Entity
do you get any errors?
oh bruh fr
how do you expect to specify a value for T ?
no
idk then
They want a donut shape.
@pliant mist My naive first thought is use OnUnitCircle and do a Random.Range(closestRange, furthestRange) and multiply onUnitCircle by that
Vector3 center;
float size;
int ite;
int maxIte = 10000;
Vector3 FindPoint()
{
while (ite < maxIte)
{
var point = center + Random.insideUnitSphere * size;
if (Vector3.Distance(point, center) > minDist)
{
maxIte = 0;
return point;
}
maxIte++;
}
return Vector3.zero;
}```
is there a flag/filter or other mechanism to search only for all scripts that are referenced in the hierarchy? e.g. I'd like to find all scripts used by a particular prefab with several dozen objects
(also, is there a better channel for editor questions?)
im having a really simple problem but i cant work it out
using UnityEngine;
public class OneWayPlatform : MonoBehaviour
{
private Collider platformCollider;
private void Start()
{
// Assuming the collider is attached to the same GameObject as this script
platformCollider = GetComponent<Collider>();
}
private void OnTriggerEnter(Collider other)
{
// Check if the colliding object is the player
if (other.CompareTag("Player"))
{
Debug.Log("Player entered the platform trigger.");
// Disable the collider temporarily to allow the player to pass through
platformCollider.enabled = false;
}
}
private void OnTriggerExit(Collider other)
{
// Check if the colliding object is the player
if (other.CompareTag("Player"))
{
Debug.Log("Player exited the platform trigger.");
// Re-enable the collider when the player exits
platformCollider.enabled = true;
}
}
private void OnTriggerStay(Collider other)
{
// Check if the colliding object is the player
if (other.CompareTag("Player"))
{
Debug.Log("Player is within the platform trigger.");
// You can perform additional actions while the player is within the trigger zone
}
}
}
my player is just a cube and so is my platform, this code is on my platform. OnTriggerEnter but not the other two. why?
did GPT not help lol
you can tell how bad it has gotten, nope
I just dont know where ive gone wrong
You disable the collider in Enter it looks like, which makes Stay and Exit not work for it
i have an issue
i am doing a sort-of rope with hinge joint, and i am attaching my player to the last "part" of the rope
the rope is composed of multiple cylinder of scale 0.1, 1, 0.1
when moving the last cylinder, the player is deformed
when the scale of the cylinder is 1,1,1 i got no issues
is there a way to fix this ?
of course yes! but then I would i create a one way platform?
use Dot Product prob
attach things with scale 1,1,1
never attach things with scales already modified imo
separate your visuals with your root objects
wdym ?
graphics/visuals should always be child of root object
so that root can be mantained at a reasonable 1,1,1
mh, how can i attach the player to the last part without attaching it to the actual last cylinder
wdym to the last part
can you bake a scale in Unity like in UE ?
no
i dont understand how i can make the player attached to the last cylinder if the player has to be child of the root
maybe i can try adding at runtime a hinge joint on the player
what
is it possible to increase this green border size without changing the image size?
the Cylinder you are talking about the mesh right ?
just Rightclick it and make new partent
the rope is multiple cylinders with hinge joints and rigibodies
then only attach to parent
The green border is the collider. Just increase the size of the collider component
to make a child object that is called "Attach to"
it doesnt have a collider
that has scale 1,1,1
you messed up when you made cylinders not separated from the chain but eh
you mean doing this ?
Hmmm. Show that again without cropping it
right
well no
is cylinder the the one that moves?
then yea
well that was already here
yes
endRope is empty object at scale 1 1 1
what about player
Ah, UI element.
Why do you want the green square bigger?
player is 1 1 1
but when attached to endRope is has to be 10 1 10 because the cylinders are 0.1 0 0.1
to keep ratio
i have a drag function in the inventoryItem script and its based on the size of the green border but its too small
cylinders cannot be 0.1
you have to fix that
again seperate mesh from main obj
well i can make a mesh in third party editor
Ok, try messing with the raycast padding then
never have visual on your root
thats it omg
i dont understand what you mean by that
what is the "main obj"
the raycast padding is the green border apparently
Good to know haha. I wasn't sure
Glad it worked
thanks
hold up
i totaly understood that my cylinders cannot be != than 1 1 1, or my player shouldnt be parent to != than 1 1 1 objects
but then, how do i make the player like its attached ?
how do i make the player "attached" to the rope then ?
wdym how
if the "root" is somewhere else
wdym somewhere else
actual setup:
-rope
--cylinder0
--cylinder...
--cylinder4
---endRope
----?player?```
well you dont want my player to be child of a a cylinders
and rope should have a rigidbody with collider then
only resize colliders
dont resize gameobjects
unless they are visual child
"rope" only has a rigibody
wdym with "visual" ?
somthing that isnt invisible for the player ?
the rope is not a chain of hinge rigidbody ?
visual means the Graphics, like the mesh/sprite
rope is an empty GO with a rigidbody, with multiple cylinderX (each of them has: rigidbody, collider, hinge joint)
well my rope is a viusal then
the cylinders should be child of slices with the actual colliders
they are nothing more than visuals
the "slices" are the sections
i dont understand the link with how to fix the issue tho
should only be collider,rb,and hinge
i told you because your problem is parenting to something scaled will result in what you saw
scale in inhereted through parent to child
yes
so without changing the scale of the cylinders, what is the possible solutions ?
child is relative scaled to parent
what is the scale of Rope
and you are parenting object to End of Rope with scale 1,1,1
Is it more common to use this.Function() or just Function() in Unity?
then end of rope should only be child of rope
otherwise fix the cylinder scale..
not that confusing
but if i do this, the "endRope" will not be at the end when moving
this is almost never needed unless you have naming conflict (eg your parameter has same name as memeber field)
or you're passing/registering yourself(the script) to something
Function() is more common, and is convention, in C# (not just unity)
Is there a way to have code activate when there is a collision (im new to unity and c sharp)
yes
did you google, there are dozens
well if cylinder 4 has a rigidbody with hinge and moving then obv it need to be attached to cylinder
but you have to fix the scale
idk how else I can explain it tbh
everytime i google something with unity i get rly conveluted results i figured ill ask first
ill try google
okay
seems weird that there is no solution that having 1 1 1 scale
feels limited
having lag issues in main game any common reasosns/fixes?
no you just don't know how to separate visuals from root
get used to doing it
before i leave, what scale is using unity ? so i can model 3D object it another sofware without rescaling ?
1m
ok ty
you have to debug/ Profile. every project is different
how do i do that?
like what ?
Massive blocks of code for simple tasks usually but ive found a good website for this
lookup Profiling
Btw do u know any good rescources to learn C sharp outside of unity
It would be pretty helpful to understand the language itself
ty ty
microsoft website
@rich adder this is what i got
it works fine in the engine but as soon as i build and play the game it starts lagging
then you have to debug the build
profile it
put it in devmode and connect it to profiler
watch a few videos on this , profiler is quite complex but tell you exactly whats going on
can anyone help me with this? my canvas text isnt showing at all even though it is first in the sorting layer?
ok ok ty
not a code question
oh sorry where do i get help?
probably #📲┃ui-ux if i was to take a guess
thanks alot
i have a problem i think it has to do with the settings from it but my particles do not start when i am just in Game view but they do when i am aswell in the Scene view. do someone know how to fix that?
#💻┃unity-talk
also if its 2d make sure they're infront of the camera
How can I do this in C#. Instead of looking up by string I want to look up by variables but I want it in a child called "actions", like this:
InputAction pauseGameAction = PlayerInputHandler.Instance.actions.pauseGameAction;
Instead of:
InputAction pauseGameAction = PlayerInputHandler.Instance.pauseGameAction;
this is prob not code related though, wrong channel
i dont know where to ask then?
i linked you
there is also #✨┃vfx-and-particles
okay thx
Best way to create one way platforms with 3D rectangles?
idk about "best" but you prob use dot product
combined with a OnTrigger for check if collider still crossing
how do I check the tag of a solid collider colliding with another solid collider?
does 3d not have triggers?
3d does have triggers.
And when you say check the tag, do you mean in OnCollision or OnTrigger?
If the former, collision.gameObject.CompareTag()
If the latter, collider.CompareTag()
Im trying to add a greyscale filter to my code but my screen just becomes either black or pink, the problem cannot be the shader, as ive tried it with a blank one.
using UnityEngine;
public class greyscale : MonoBehaviour
{
private Material mat;
public Shader shad;
public bool grey = true;
// Start is called before the first frame update
void Start()
{
mat = new Material(shad);
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (grey == true)
{
Graphics.Blit(source, destination, mat);
}
}
}
!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.
how do you call a function from another script, nothing i looked up seems to work or be in date
You need a reference to the other script
calling functions from another script hasnt changed since c# was around..
how do i add it, ive been getting a barrage of error messages using getcomponent
Add a field, something like "public YourScript myScript" should do it
Don't worry about [SerializeField] for now
Hi Guys i need help the code under //1 and //3 works but for some reason the code under //2 dosent work
https://pastebin.com/VHefRLzf
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.
Can someone help me for this script, yesterday i got told that i need to do this but it didn't work
start by properly closing your brackets
i didn't see this lul
like this?
should i change it or just for next time?
what are arrays used for in Unity? Know what they are from Comp science knowledge but curious as to how its used
i can imagine inventories
they are just collections
is spawning a script on each individual bullet to move it inefficient? is there a better way to code this?
you literally use collections in everything substantial you do
probably. just put a rb on it and make it move from gun itself
you still need scripts on bullets anyway if you want to do on impact fx maybe
i couldnt think of a way to do this within update as there would be multiple bullets at once
especially with the collision
what exactly you expect to happen with //2
when you spawn something you literally get its instance
but anyway at level you're at don't worry about it
okay, ill just stick with multiple scripts then
if it gives you problems profile it later
the only other thing i was gonna try was a list of the bullets and looping through them each time but that freaked me out a bit lmao
thanks for helping
this is actaully the concept of pooling. You recycle the same bullets for perfomance
instantiating and destroying is expensive in comparison
how would you implement though do you just use it in scripts like in other programming stuff or is there a certain component (or something of the sort) for it which you would add to something like an empty manager
you use them like any other languages usually
when two of the same touch the spawn the boy3 prefab but when they touch they just bounce off
Why is my visual studio using 4GB ram lol
oh yeah did you install any updates for it?
What’re u running xD
Nothing, just have 4 scripts open
well you got a lot going on there, you have to debug
are the other ones working ?
yes
but i forgor some code
https://hastebin.com/share/obatohofiw.scss code i forgot
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
debug your if statements make sure they are what you expect them to
myb nvm
Could have quickly just looked it up yourself too
They are trying to change the key based on a variable, the IDE is not helping with that
public KeyCode Key would be the most sensible way, instead of trying a string
ohh wops just saw that field
screenshot was cut for some reason 😅
doesn't work
:(
although you can see editor which type you would need to store @clear seal
show what you did
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerOneSoccerScript : MonoBehaviour
{
public float speed = 10f;
public float Rotation = 10f;
public KeyCode Key;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (!Input.GetKey(KeyCode.Key))
{
transform.Rotate(0, 0, Rotation);
}
else
{
transform.position += transform.up * speed * Time.deltaTime;
}
}
}
`
Key is a keycode already, no point of typing keycode twice
Just pass the Key variable to the function instead of trying to use it as an accessor to KeyCode
Also, use three ```, not one of them for a codeblock
@clear seal
btw if you plan on using collisions, you should probably not move like this
transform.position += transform.up * speed * Time.deltaTime;
ok thanks
This might sound dumb, but do you guys think i should make a prefab out of this
And when a player is spawned
it just spawns the prefab
Bcs rn i just have the player forced on the map right
making player prefab is fine
I have two boxing ai that are hitting each other and I want to do a check on collision enter to see what part of the other fighter the boxing glove hit
Hello. I am struggling with a smooth rotation
void Update()
{
// Moving towards waypoint
Vector3 dir = target.position - transform.position;
transform.Translate(dir.normalized * (speed * Time.deltaTime), Space.World);
// Frontside of the enemy looks towards the next waypoint
Quaternion lookRotation = Quaternion.LookRotation(dir);
// Smooth rotation
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
// Has enemy reached the waypoint ?
if (Vector3.Distance(transform.position, target.position) <= 0.2f)
{
GetNextWayPoint();
}
}
Right now, the enemy looks towards the next waypoint and does a smooth rotation after he reached the waypoint. But I want that the enemy begins the rotation before he reaches the waypoint. For example 0.5seconds before he reaches the waypoint, he starts the rotation. So the rotation time is equal before and after the waypoint. How do I do that?
so I'm doing this
if (col.gameObject.tag == "boxingGlove")
{
Debug.Log(col.gameObject);
}
but it's logging collisions before the fighters even start hitting each other
what is it logging in name ?
So from point A-.-B---C you want it to start rotating towards C at the . symbol?
yea
Exactly. Enemy starts at A. Starts the rotation slightly before B. And finishes the rotation slightly after B. Looking/rotating towards C.
hand, lower arm, chest, spine, head
idk what those mean ..
i have no context on your setup
somehow there are a bunch of collisions between the boxing glove and parts of the gameobject it's attached to
and I want to filter those out
do you have joints?
yes
And does the time until it starts rotating to C have to be in seconds, or at like half the path? Like if the distance from A to B was 20, do you want it to start rotating to C at travelDone = 10 or when there's literally x amount of seconds until B is reached?
I want to only check if it's hitting the other boxer
thats why they intersect
use layer based collisions
or put Physics.IgnoreCollision method inside
why calling randomshootangle() does not change the value in each loop
will this affect the physics or just the detection in code
cause I don't want the different parts of the gameobject to stop colliding with each other
are the colliders meant to collide with each other
very yes
I just want a way to differentiate them without putting a unique script on every sub-gameobject
It would be better if the unit is in seconds because if it's always half the path, then the rotation time depends on the distance between each waypoint. That wouldn't be so helpful because the distance between two waypoints can differ 🙂
put them inside a list of colliders the one you want ignored and do a foreach loop in the beginning with the Physics.IgnoreCollision @ashen wind
Then I believe you could do some sort of prediction in the pathfinding agent while it's moving to see, using the seconds as a factor, when it would reach the path point x
Then start rotating when it does
[SerializeField] private Collider[] collidersToIgnore;
[SerializeField] private Collider[] boxingGloves;
private void Awake()
{
for (int i = 0; i < boxingGloves.Length; i++)
{
foreach(var col in collidersToIgnore)
{
Physics.IgnoreCollision(boxingGloves[i], col, true);
}
}
}```
but what does physics.ignoreCollision do? won't that stop them from colliding with each other?
A prediction? Do you mean some sort of checking whether the enemy is x-meters away of point y?
i dont get it, i searched for a tutorial, none respond to my demand, i asked some friend, they dont rlly know abt unity scripting
yea isn't that what you want?
Also (little off the rails), to make the script more consistent, I recommend you to use Transform.MoveTowards() instead of Translate, because the latter can overshoot, thus the reason why you have an epsilon distance check in the end of that snippet
if (!Input.GetKey(Key)) ?
inside the oncollisionEnter function, I want a conditional that checks if the thing the boxing glove is hitting is a body part of the opponent
time to go back on basic C#
I don't want the physics to operate any differently than it does
make an Enum
i am currently learning on unity. learn and none mentionned it
You could take the speed of the agent, multiply it by seconds (this gets you the amount of distance covered in x seconds), then when that distance is bigger than or equal to the actual distance to the path point you initiate the rotation logic
this is more like something you learn better doing regular c# courses
passing values/types in the parameters is like essential stuff you need to know
you mean attach a script to every child gameobject with an enum in the script?
This would get more complicated if you have some slowness/speed systems in place but assuming you don't, it should work like this at a high-level
sorry meant to quote the other reply I made
no? you can just check the parent of the collider hit..
I intend to add towers which slow enemies. Does this interfere with your logic improvement thing?
but there are a ton of parents, and even the top gameobject is parented to the environment
why are player parented to environment
and it doesn't matter cause its the first script it finds (GetComponentInParent) for example
you only need 1 script on the appropriate player
Well, one way I can think of having this be accounted for is using a ratio of travel left for the rotation logic, with the ratio being something like "current travel left / started rotation at travel left"
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
public float speed = 10f;
public float rotationSpeed = 5f;
private Transform target;
private int wavepointIndex = 0;
private Waypoints waypoints;
void Awake()
{
waypoints = GetComponentInParent<Waypoints>();
if (waypoints != null)
{
target = waypoints.points[0];
}
else
{
Debug.LogError("Waypoints script not found in parent objects.");
}
}
void Update()
{
// Moving towards waypoint using MoveTowards
Vector3 currentPosition = transform.position;
Vector3 targetPosition = target.position;
transform.position = Vector3.MoveTowards(currentPosition, targetPosition, speed * Time.deltaTime);
// Frontside of the enemy looks towards the next waypoint
Quaternion lookRotation = Quaternion.LookRotation(targetPosition - currentPosition);
// Smooth rotation
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
// Has enemy reached the waypoint ?
if (Vector3.Distance(currentPosition, targetPosition) <= 0.2f)
{
GetNextWayPoint();
}
}
// Getting the next waypoint
void GetNextWayPoint()
{
if (wavepointIndex >= waypoints.points.Length - 1)
{
Destroy(gameObject);
return;
}
wavepointIndex++;
target = waypoints.points[wavepointIndex];
}
}
I implemented your "Move Towards" suggestion and it works just fine (for now) 🙂
Also, you no longer need the "if (distance < some value)" check, just check if it's literally the target position because MoveTowards is that accurate
Distance uses sqrt under the hood so better save performance that way
use links for large code like this
Hellooo
How can I make this folk stop bouncing? And how can I make it face the player?
depends?
Dafuq is this?
It's using a velocity set to move towards the player
Probably a hub for hosting Visual Studio services on any CPU
What services
then its probably wrong or you're using conflicting forces
Idk, maybe some Chinese tracking software or something
jk
also google rotate object towards target in unity
Thaanks
Is this normal?
Have you tried googling that?
can someone help me with this random seed issue?
@wild cargoWell it could be normal since the intellisense is pretty advanced. And don't everyone in here use visual studio?
Yeah that's prolly it, and most probably also use VS but others may use some other IDE like Rider
Depending on their preferences
It doesnt look like you use the angle you provide, I woul maybe just return something like angle + Random.Range(-spread, spread), then log what the result is, its also possible the spread from your weapon is small or the same number
im having trouble with my camera, the little window that shows what it sees isnt accurate and when i zoom the camera out, everything is pixelated
My rotation issue never got fixed.
im having trouble with my camera, the little window that shows what it sees isnt accurate and when i zoom the camera out, everything is pixelated
<@&502884371011731486>
!mute 1038535490133037127 1d spam
azedev was muted.
Thank you.
make sure that your Game View window isn't zoomed in
also this is a code channel
thank you i almost gave up to such a stupid thing
I've got a quick question about the unity line renderer. Does anyone know why it doesn't change the line to the color I set?
The only way to change the rays color is to give it another Material
Can someone tell me why when I click ctrl p it deletes my changes every second time?
this is a code channel
ah, sorry, my fault
where should I post my question instead? Can't find a suitable channel
you have to find the solution yourself
maybe #✨┃vfx-and-particles or #💻┃unity-talk
i know the tansform movement doesn't work with colliders and rigid body
i got a problem there
how do i make it move so it does not go trough the objects
is it just me or is coding a fully working inventory that works like one in minecraft unexpectedly difficult
i was thinking it will take 2 days max or am i just slow
is it okay if i say it's not okay?
Not without showing your work
hold on trying to make some possible correct changes
public class PlayerOneSoccerScript : MonoBehaviour
{
public float speed = 10f;
public float Rotation = 10f;
public KeyCode Key;
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (!Input.GetKey(Key))
{
transform.Rotate(0, 0, Rotation);
}
else
{
transform.position += transform.up * speed * Time.deltaTime;
}
}
}
here you go
at no point here are you attempting to move via the rigidbody. you're also not even using the right type of rigidbody
oh yeah i forgot to remove
there were even examples in the link 😔
I'm trying to alter my zoomspeed but it doesn't matter if I set it to 100 or 10000, it is equally fast...
cinemachineVirtualCamera.m_Lens.FieldOfView = Mathf.Lerp(cinemachineVirtualCamera.m_Lens.FieldOfView, zoomValue, zoomSpeed);
zoomValue = 1f, zoomSpeed = 50f to 10000f
Also tried with deltatime
public abstract class CardEffectTriggerSO : ScriptableObject {}
Would an empty class in Unity be acceptable if it is a base for ScriptableObjects? Generally, there is no good excuse for empty classes, but I just need to be able to select CardEffectTrigger SOs from other SOs
There's no law against it, so you're not gonna go to jail for doing that🤷♂️
im doing the exact same but with delta time and it works
What is zoomSpeed equal to?
It needs to change from 0 to 1 over time for a proper lerping.
Should probably read a bit about how lerp working.
yeah he needs to multiply by time.deltatime
No, he doesn't.
That might work since it brings the value under 1, but it's still not a correct way to lerp.
public class Camera : MonoBehaviour
{
[SerializeField]
private GameInput gameInput;
[SerializeField]
private float zoomSpeed;
[SerializeField]
private float fieldOfViewIncreaseAmount = 4f;
[SerializeField]
private float fieldOfViewMin = 10f;
[SerializeField]
private float fieldOfViewMax = 80f;
private CinemachineVirtualCamera virtualCamera;
private float targetFieldOfView = 34f;
private void Start()
{
virtualCamera = GetComponentInChildren<CinemachineVirtualCamera>();
}
private void Update()
{
HandleCameraZoom();
}
private void HandleCameraZoom()
{
float zoomValue = gameInput.GetZoomValueNormalized();
if (zoomValue > 0)
{
targetFieldOfView += fieldOfViewIncreaseAmount;
}
if ( zoomValue < 0)
{
targetFieldOfView -= fieldOfViewIncreaseAmount;
}
targetFieldOfView = Mathf.Clamp(targetFieldOfView, fieldOfViewMin, fieldOfViewMax);
virtualCamera.m_Lens.FieldOfView = Mathf.Lerp(virtualCamera.m_Lens.FieldOfView, targetFieldOfView, Time.deltaTime * zoomSpeed);
}
}
this is my camera class and the zooming works fine (zoomSpeed is 2 in the inspector) your speedvalue might just be too high
Did you even read my message? It needs to from 0 to 1. If it's above 1 it's gonna be the same as 1.
This is incorrect way to lerp.
it will never reach above 1 though
how would you go about creating a checkpoint system similar to the one present in games like doom(i essentially need the map to be loaded to the same state it was in when a checkpoint was passed)
They are setting it to values above 1.
You need to implement saving/loading system and then combine it with triggers in the scene to trigger saves.
do you mean in my script
@teal viperOkay, how to zoom faster than 1?
saving/loading the map? ive implemented that type of system for the player but i cant figure out how to do it for the map
No. It was a response to Zyme.
Your script still does linear interpolation incorrectly though.
You seem to not be listening.
How do you think lerp works?
ive tried saving the data for the triggers in a dontdestroyonload object but then the address for the triggers gets changed when the map reloads
thats not possible
but 1 is already insanely fast so theres probably something wrong in your setup
@teal viperSo I cant have a fast and smooth zoom with lerp
What should I use instead?
Yes. You need to save all the state that you want to save. And I don't get what you mean by saving data for the triggers and why that would matter.
Yes you can. Can you answer my previous question? Tell me how lerp works.
i meant basically what you said by saving state, but after i save state how would i load these changes back into the level when the scenes loaded again?
After loading the scene, check if there is any saved data to be loaded, if there is, load it and adjust your scene accordingly. If it means spawning enemies at exact locations in certain states, do that. If it means repositioning the player and adjusting it's ammo, health and other stuff do that as well.
when im saving the data how would i load it back into the level if the scene is reloaded, when ive tried loading the saved data back in i would get null references.
i tried having code that would add anything that would need to have its state saved to a list in a dontdestroyonload level manager but since everything was loaded again any references it had would be gone
It would need to be saved to a file or stored in a place unaffected by scene unload(like DDOL or static fields)
You don't save references. Consider that all of the objects in a reload scenes are entirely different objects.
Basically, you save plain data and then use it to recreate the state(create any new instances of needed). If you need to get a reference to an existing object for some reason, you could save it's I'd and get it by the Id at loading time.
okay that makes sense i was just wondering what format i would be saving it into
so it could be read after
Json or binary if that's what you're asking. Xml is also an option I guess.
can someone recommend me a book or video series to learn about clean coding especially game code?
things like when to use interfaces, recursive methods, structs etc?
i mean like what variables would be used and how it would be set up to take in the data from the files and make something from it
like if i didnt want a barrel to reload
after its destroyed would a new line be created in a file with a copy of its id and the bool thats triggered be sent to the file
and that be used to recreate state?
Then you save it's state as destroyed:
public class objectState
{
int objectId;
int onjectState; // 0 for destroyed
}
Then, when loading the data you get the object by ID and if it needs to be destroyed, you destroy it. The example I provided is very plain and real code might need to be a lot more complex than that, but the idea is the same.
ahhh yeah that should be fine thank you
just to make sure that would be present in the script of the object and not be its own class right?
It can be either. It depends on how your loading system works. Usually, you'd serialize/deserialize a plain class like that with JsonUtility or something.
When you're saving, you could iterate all the savable objects and call something like:
ObjectState objectSaveState = savableObject.GetSaveData();
string saveString = JsonUtility.ToJson(objectSaveState);
//Write the string to file or combine it with other save data
ight i see what you mean thanks
!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.
for the objectIDs here though, when loading these back in how would you go about comparing the ids to objects in the scene.
You could keep the objects in the scene that need saving/loading in a dictionary where the ID is the key. Or if the Id is simply a number from 0, then they could just be in a list/array. Then use the Id as the index.
ohhhh
In a GameManqger/SaveManager or something.
so i would have the data loaded to the level manager
the dictionary would be on the level
and on load the data would be transferred to the level and state would be set then?
Sounds about right.
Well, saving systems can get pretty advanced, so it's not an easy topic for beginners.
im not familiar with enums so how do I reference the enum from another script. myType is the enum variable on the stats script. im trying to check if the type is Player or Enemy
im trying to acess it from the myStats script but can't seem to figure it out
== EnumType.Value
I don't know why I get 2 errors. Can someone help me? I'm trying to do the SlowMotion when I press the V key and this comes up.
Show us the console errors
wow, "Application.Quit();" doesent work anymore in the latest 2023.2.3f1 version.
Hello dear player,
please press ALT+F4 in the future because exiting the game via Exit button will no longer supported anymore.
and have you added the namespace?
Just use your IDE to add it via its suggestions
Are you testing this from the Editor or the application?
I am testing the uploaded depot on Steam.
What platform?
Windows x64
Not sure. Docs say it's perfectly fine outside of the Editor and with exclusion of iOS.
There's nothing in the issuetracker about it
Maybe you've got something else going on.
I did not touched anything since Unity 2021 and it worked everything fine there. Then I updated to the 2022LTS and to the latest 2023f1 and now the exit button doesent work anymore.
LIke I was known it earlier on the linux build of Unity 2021.
Well, check for a borked button, an exception occurring before your quit call, returning false in wantsToQuit
If none of those, test it in a blank project and report a bug
I have been watching and kind of blindly following code i dont really understand. Is there something im doing wrong in the learning process?
Yes. The moment you realize you don't understand a line of code, stop there and research it until you understand it.
Yeah, the blindly following
im familiar with most basic things in unity, and the simple code and syntax, but when it comes to using any of it i suck
ill try that method
Well, I made a fresh new project with just a exit button and quiting worked just fine, but I also made a print("ApplicationQuit was Executed."); over my Application.Quit in my Main project and see atleast in the Unity Editor console, my Code does reach it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Management;
public class ExitGame : MonoBehaviour
{
private AudioSource audiosource;
private bool beendenaktiv = false;
private void Start()
{
audiosource = GameObject.Find("snd_Buttonclick_Ausgabe").GetComponent<AudioSource>();
}
public void StartTheEnd()
{
audiosource.clip = Resources.Load<AudioClip>("click_mainmenu");
audiosource.Play();
beendenaktiv = true;
}
private void Update()
{
//Solange die AudioSource eine .ogg abspielt, wird die Anwendung nicht beendet:
if (!audiosource.isPlaying && beendenaktiv == true)
{
// Das beenden von XR hat zu folge beim beenden des Spieles, das der Standard VR Home
// geladen wird und die VR Brille nicht stuck ist!
if (XRGeneralSettings.Instance.Manager.activeLoader != null)
{
XRGeneralSettings.Instance.Manager.activeLoader.Stop();
XRGeneralSettings.Instance.Manager.activeLoader.Deinitialize();
Debug.Log("XR also stopped by Quiting Game!");
}
beendenaktiv = false;
print("ApplicationQuit was executed.");
Application.Quit();
}
}
}
Does it hit it in the build though
it wont exit in unity, if you run the game as an application it should execute whatevers there
I think so?
Atleast the console says that Apllication.Quit does get reached by pressing the button. so why not in the build?
It wont exit, but it will reach the print
so why not in the build?
I don't know, that's why you need to test
go to build settings and see if all the scenes are added.
You've got to drop any assumptions you have to figure out where things are breaking
One important element of understanding the code is answering the question "what does it do in the context of the whole algorithm?" And "why this code and not different? What does it contribute to the whole program?"
yea, im thinking im just not seeing the code enough, like school you study one thing multiple times, but trying to build the smallest of games is difficult bc im doing everything in one go
Yep. You should slow down and break down your code.
OK I did.
Its all the XR stuff thats keeping the game away from quiting.
/*if (XRGeneralSettings.Instance.Manager.activeLoader != null)
{
XRGeneralSettings.Instance.Manager.activeLoader.Stop();
XRGeneralSettings.Instance.Manager.activeLoader.Deinitialize();
Debug.Log("XR also stopped by Quiting Game!");
}*/
after I commented it out, quiting was now working.
what kinda games should i look to make to start out? i made flappy bird, cubonics, and a million other attempts at harder games.
oh, pong as well
Maybe instead of working on a new game, go back to these projects and try to implement some changes.
good idea, ill try that now
How do I make an array to make an object a random color?
Color[] or Color32[]
For the former, get three random values between 0 and 1 (probably between .1 and .9 to avoid white and black)
For the latter, three values between 0 and 255
But how do I make the sprite the color I want?
Since this is the programming channel, I'll only target the programming aspect of game development.
How do you feel about C#. It'll be great if you're comfortable with Procedural and Object Oriented Programming.
Have you worked with other libraries/frameworks before? Most would likely introduce you to patterns of subscribing-to/implementing callbacks and whatnot.
If you're fine with the two above, the remainder of what you'd learn from tutorials would mostly be about how specific tasks are approached and interacting with a particular types.
.color =
Then don't do it randomly I guess. If you mean a pallette, then just change the colors in the array. Get a random index from it
What do I put before the .color?