#archived-code-general
1 messages Β· Page 283 of 1
Elder Camel System?
probs just a simple answer but im making like a vinyl player and its as simple as making an event for each like "disc" that activates music when played ye?
what's that?
What does ECS stand for again?
entity component system
what Burst-compatible ways are there to move my camera position to the position of a LocalToWorld component? I get this error (the code works but the error appears and I don't like it):
Burst error BC1016: The managed function UnityEngine.Transform.set_position(UnityEngine.Transform* this, UnityEngine.Vector3 value) is not supported
my camera isn't an Entity but I have stored a reference to it with code
a.SetActive(false); is making my ar not show in game anybody that could help ,e
Yes you're deactivating it so it gets deactivated. What's the issue?
hey does anyone know how to convert quaternions to degrees?
google hasn't been really helpful
In what way? Quaternion has a .eulerAngles property if that is what you need
oh i just need to convert transform.rotation.x to degrees
transform.eulerAngles.x
ohhhhhhh
Yeah transform also has eulerAngles. Same as typing transform.rotation.eulerAngles
Is there a way for a raycast to target (or ignore) multiple layers at one?
Yes, layer mask can contain multiple layers
ah thanks!
uhh is there a way to make it display 5 instead of 355?
I like to use Mathf.DeltaAngle(0f, angle) to convert an angle into -180...180 range
it just doesnt show
ohhhhhh thanks
should i make it true_
It gives the fastest angle from the first parameter which is 0 in this case
Wait do you want -5 or 5?
5 but im inverting it
Oh nvm that's -355 so 5 yeah
it works perfectly, thanks
however um do you happen to know why my stuff tend to clip through things at times?
like if i go 25+km at a wall or the floor it will phase through?
Do you have a rigidbody and how are you moving your objects?
2D or 3D?
vector3
So it's Rigidbody and not Rigidbody2D?
Should try using velocity or AddForce instead to move it
but it still happens even when i let stuff fall with gravity
MovePosition doesn't really give accurate collision AFAIK
i made a drone and when it falls out of the sky half of the time it phases through the ground plane
Don't move it with MovePosition π€·ββοΈ
ill give velocity a try
You need to keep your previous rb.velocity.y if you don't want to override the gravity
Am I missing something? (output in image)
if (_groups[group].Count < currentIndex + 1) return null;
Debug.Log("count: " + _groups[group].Count);
Debug.Log("index: " + currentIndex);
return _groups[group][currentIndex + 1];
movePosition is so goofy
You log currentIndex but check currentIndex + 1 which is not less than but is equal to Count. Both values are 2 . . .
AFAIK MovePosition and MoveRotation are designed for Kinematic rigidbodies, where Unity assumes youll handle physics yourself, but when using velocity or AddForce, then Unity handles the physics for you, and its best to use these things in FixedUpdate as thats the rate Unity will check for physics collisions - if the object is moving really fast (for example like a bullet), you could also interpolate the movement, which will try to predict collision a frame ahead of the velocity
yeah they are all in fixedupdate but it still happens
ill try the other two later
i mean i'll probably change the system entirely
but thanks for your input
did that HDRPPACKAGE_EXIST symbol get added to your player settings maybe? you might need to manually remove it
I followed this video on how to get 0-G traversal for a spaceship working in which he used UnityEngine.Input to map controls. My issue is that these are based on the X and Y axis which works for WASD in that system. How would I get this working for Input system? Guides aren't clear.
float yAxis = Input.GetAxis("Vertical");
float xAxis = Input.GetAxis("Horizontal");
ThrustForward(yAxis);
Rotate(transform, xAxis * -rotationSpeed);```
Trying Copilot for some code advise. It tried getting me to put WASD and the LeftStick controls under one Action in my Action Map, but that still wouldn't give me the X and Y
private void ThrustForward(float amount)
{
Vector2 force = transform.up * amount;
rb.AddForce(force);
}
private void Rotate(Transform t, float amount)
{
t.Rotate(0, 0, amount);
}```
the two called functions are like this. The Axi aren't called in the below code. Edit: No its just a 0 -1 or 1 pretty much. 0 means no press and no force to be added, 1 means positive force, and -1 means negitive force
You can get the value of an Action provided it has the correct type with InputAction.ReadValue
Assuming your action is a Vector2, you can do yourInputAction.ReadValue<Vector2>()
And it will know that WS is Y and AD is X?
My confusion comes from this:
float yAxis = moveAction.ReadValue<Vector2>().y
How would it know WS are y values.
When you set up a vector 2 input action in the editor, it has a Up Down Left Right component. Up/Down is Y and Left/Right is X
If you created it through code, you just have to bind it correctly
Do you bind it in the Action editor or through code
If you have an InputAction asset, do it through the editor. If you created one in code only, you do that there
So like this?
On my player character I've made a lot of variables to have [SerializedField][ReadOnly][Foldout("Debug states")] attributes ("Read only" and "Foldout" are attributes from Naughty Attributes addon), to monitor their values and see how my logic behaves. I've noticed that whenever I select my player object during playmode, the performance starts to lag quite noticeably.
I guess that's because I have too many serialized fields on a display in the Inspector so it struggles with updating them every frame, but if it so, are there any other ways I could monitor state of a lot of variables at once in realtime in Unity editor? I have a comparable amount of debug-exposed variables on my NPC scripts as well, so I suspect it would cause the editor to lag as well, though I didn't test that yet.
It's editor lag. Do you need to constantly check so many fields at once?
Have you tried displaying the values with ugui on a single canvas that you can show/hide with buttons for different groups (instead of a colossal list)?
I thought I would waste too much time coding that ugui versus simply sticking [serializeField] on a variable, and I'd need to update it each time I add a variable to the "watch list".
I don't know if I need to watch so many variables, but when I'm playtesting my player controller, or NPC, and suddenly things don't work as they should, I want to inspect what exactly is the state of the object to understand what caused it to go wrong, since most often the issue is not a code error, but in logic flow. Can't do that with a regular break points in code since those issues are situation-specific and involve code that executes pretty much every frame or every fixed update, so any break point would be triggering constantly, making game unplayable.
Maybe do some profiling to see what exactly causes the lag
Does profiling includes editor, or only game code?
You can profile the editor
Profiling Play Mode in the editor will only record detailed information for Play Mode, but it does also measure how long the editor loop is taking
It can also be unreliable
I've seen cases where the play loop was allegedly taking only 3ms (it's more like 10)
i think a bunch of stuff was getting stuffed into EditorLoop
I have a very fast moving object and its rigidbody is not colliding even though I set the collision to contiguous any idea why?
continuous or continuous dynamic?
continuous dynamic
Does it also rotate? Does the other colliding object move or rotate as well?
@static matrix static in the sense that they do not have a rigidbody?
static as in the sense that they do not move
they technically also do not have a rigidbody
@static matrix what is the collider type on the dynamic object
Also, how are you moving it?
How does Debug.Log take virtually any parameters without the user ever needing to use <T> jargon?
True, but there will be some inconvenience with either method. Most people will have an in-game console or debugger to do that, especially since running in the editor with the inspector will slow down the game
You can test this. Maximize the screen during runtime. The game will run smoother than in window mode with the editor visible
I'd remove variables that you've already tested or group them into smaller foldouts to avoid a heaping list of variables . . .
It calls ToString of the objects that you pass in.
It takes an object parameter. Everything is an object . . .
There is no need for generics . . .
wait.. so you can make Object be a parameter type... what... woah...
that's mindblowing
Why? It's a type . . .

@icy depot Note the difference between object and Object . . .
You can have a void* as a parameter in C++. Now that's mind blowing... The first time you hear about it.
you... can...?
Yeah. There's a lot of stuff you can in programming.
wait what's the different? which one's the type name?
object is an alias to System.Object afaik.
oh wait so object is a type name just as lowercase float and int are?
I'd switch to raycast or a XXXCast or a physics OverlapXXX method . . .
ah yes mister . . .
They are both types. object is a C# type; Object is a Unity-specific type . . .
oh!
Yes
ohοΌοΌοΌ
then, does void also have an official name?
also how do you do the spaced dots?
oh wait
. . .
There's System.Object and UnityEngine.Object
No. void is just lack of type
oh.. so void's just syntax
System.Void is a type
Yeah, those are the types I'm speaking of . . .
I just didn't write their fully qualifying names . . .
Removing is an option, though IDK if further grouping is gonna help, since I think the very fact that they need to be displayed at all is what causing lag.
If a foldout hides the fields they won't be drawn in the inspector, only when that foldout is open . . .
I need to get the 0, -1, and 1 values from ThrustControl > Vertical || Horizontal in my code. How do I call the Composite Behavior in code?
I'm confused. Is this a 1D axis or 2D?
1D axis according to the Composite Type
sure but why
Why what?
Why have two different 1D axis for horizontal/vertical
instead of a 2d axis?
What are you trying to do here exactly?
private void Update()
{
float yAxis = playerControls["Vertical"].ReadValue<float>();
float xAxis = playerControls["Horizontal"].ReadValue<float>();
ThrustForward(yAxis);
Rotate(transform, xAxis * -rotationSpeed);
//Store ship data for UI
currentVelocity = rb.velocity.magnitude;
currentHeading = rb.rotation;
}```
I am trying to modify some code I made for Zero G traversiel in which I need to call a value to find whether the user is giving a positive or negitive Y and positive and negitive X to trigger my players rotation and Thrust
You are overcomplicating this
Select the ThrustControl axis and set it to:
Action Type: Value
Control Type: Vector2
Remove your existing bindings
Make a single binding of type "up/left/right/down composite", and bind all four buttons to it
Sorry fairely new to Input System
Yes I know that and I'm helping you
I Thank you for that π
then in your code you will do cs Vector2 thrustInput = playerControls["ThrustControl"].ReadValue<Vector2>();
you can then do whatever you want with that - including reading thrustInput.x and thrustInput.y
Am I able to do a ULRD composite separately for gamepads aswell for this?
yes
can some 1 help me whit fixing a script
Provide your code, first and explain the issue
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public bool hoverd;
public Item heldItem;
private Color opaque = new Color(1, 1, 1, 1);
private Color transparent = new Color(1, 1, 1, 0);
private Image this slotImage;
public void inistialiseSlot()
{
thisSlotImage = gameObject.GetComponent<Image>();
thisSlotImage.sprite = null;
thisSlotImage.color = transparent;
setItem(null);
}
public void setItem(Item item)
{
heldItem = item;
if (item != null)
{
thisSlotImage.sprite = heldItem.icon;
thisSlotImage.color = opaque;
}
else
{
thisSlotImage.sprite = null;
thisSlotImage.color = transparent;
}
}
public Item getItem()
{
return heldItem;
}
public void OnPointerEnter(PointerEventData pointerEventData)
{
hoverd = true;
}
public void OnPointerExit(PointerEventData pointerEventData)
{
hoverd = false;
}
}
idk whats wrong whit it
btw you can put code in a codeblock with three `
what?
!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.
Thx
I'm looking to check if a coroutine is running. On the internet, I found that you could just be straightforward and make a bool for each coroutine. Is there a more efficient, or should I say, cleaner way to know if a coroutine is running or not?
private Image this slotImage; this should be showing an error.
And, what would happen if I tried running a coroutine that's already running>?
If your IDE isn't underlning things. You need to configure it !ide @hallow current
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
it will start running another instance of that routine
so.. two instances will be alive?
yeah
that would suck...
if you do a start couritine during update it will start a new courutine every frame
which is something you would want to avoid
Store the coroutine in a variable and check if it's null. Null = not running . . .
wait, so null means it's running or not? that works?
I had that in my code originally but it was just intuition
so why isn't it the first result when I look the matter up? weird..
You'd assign null to the coroutine variable at the end of the coroutine method (indicating its finished) . . .
ohhhhh!
time to go do that
wait.. while it's running? that works? well i suppose..
coroutines are weird...
It's just a variable
So it doesn't matter what you assign to it, it won't affect the coroutine
@icy depot i made an utility function that can be used to be able to have courutines start in update without creating new instances per frame
/// <summary>
/// Execute logic once
/// </summary>
/// <param name="logic">The logic to execute</param>
/// <param name="wasExecuted">Set the referenced bool to false to execute again</param>
public static void DoOnce(Action logic, ref bool wasExecuted)
{
if (!wasExecuted)
{
wasExecuted = true;
logic.Invoke();
}
}
You assign a Coroutine variable when you call StartCoroutine. You can check if that variable is null. Inside the actual coroutine method, you assign the same Coroutine variable to null. This indicates, it is no longer running . . .
its a delegate that returns nothing
basically a void function as a parameter
Did you solve it? How fast are we talking? Is it moving in a straight line?
In layman's terms its a function to call other functions
When you Invoke a Action / Func the functions that were subscribed to it get called
you use it like this
DoOnce(() => { /*your logic here*/ }, ref yourBool);
that's some funny syntax that i've never worked with
so you can call a whole function in a function
they are called lambdas
That's a lambda expression not the same as a Action
what exactly does => do in a broader scope?
its valid syntax, Actions are delegates
So you know how Methods have parameters maple?
The () is the method parameters in the sense and the => is the body of the function
You got it!
thats just lambda syntax the paranthesis hold parameters like in a normal function, if there are no parameters you just have empty parameters

the => basically declares the body
if there was a parameter or two, how'd it look?
Keep getting a Null ReferenceExpection: Object reference not set to an instance of an object
I called thrustControl as public Vector2 thrustInput; but it seems to still error.
private InputActionMap playerControls;
public Vector2 thrustInput;
#region Monobehaviour API
private void Start()
{
rb = GetComponent<Rigidbody2D>();
thrustInput = playerControls["thrustControl"].ReadValue<Vector2>();
}
oh and I don't get the ref keyword..
(int param1, float param2) => { code }
so the type is also in!
its passing a variable by reference
basically when you give it a variable that variable can be modified inside the function
ohhhh
You didn't spell thrustControl correctly
wasn't it capitalized in your action asset? ( and my example )
It was, changed that just now but its still struggling
private InputActionMap playerControls;
private Vector2 thrustInput;
#region Monobehaviour API
private void Start()
{
rb = GetComponent<Rigidbody2D>();
thrustInput = playerControls["ThrustControl"].ReadValue<Vector2>();
}
private void Update()
{
float yAxis = thrustInput.y;
float xAxis = thrustInput.x;
ThrustForward(yAxis);
Rotate(transform, xAxis * -rotationSpeed);
//Store ship data for UI
currentVelocity = rb.velocity.magnitude;
currentHeading = rb.rotation;
}
Its giving me NullReferenceException: Object reference not set to an instance of an object AdvancedPlayerMovement.Start () (at Assets/Player Logic/AdvancedPlayerMovement.cs:26)
Did you ever assign playerControls anywhere? From your snippet it doesn't seem like it
Yeah you never assigned playerControls anywhere
Oh wait maybe not
one sec woops
playerControls = new InputActionMap("Player");
Is this not accurate?
The Action map is called Player
i dont think that is valid, you are initializing a new action map, not using the one you made
Sounded off to me aswell, but its the only layer of code I found that is trying to save an action map
the input system generates an input master script that contains all your bindings, thats probably what you want to get
I just don't know what method will fetch them
you basically want to do this
inside a manager class or something
then you can just call the INPUT variable and it contains a reference to all your maps and actions
hello i have a question is unity c# version don't have the memory<T> sturct?
Try it and see?
i don't see the struct
Then i guess it's not there
not accurate no - why not use the atuo generated class
It's not going to be called input master unless his action asset is called that
Zane if ur using PlayerInput on ur gameobject at this point it might just be easier to use the Unity Events option on PlayerInput
they don't seem to be using PlayerInput
If you want to access all of your input actions through code, turn on "Generate C# Class" on your InputActionAsset. This will create a class containing all of the action maps (which, in turn, contain all of the actions).
The class will have the same name as your InputActionAsset.
how would one go about assigning an audioclip to a static AudioClip field?
you can't serialize static fields.
A reasonble alternative is to have a singleton that holds references to things.
that's the only way i can think of
in my case i have several instances of a script that are going to use the same audioclip... i suppose a singleton is the right way to do it
[CreateAssetMenu]
public class GameSounds : SingletonSO<Gamesounds> {
public AudioClip someClip;
}
Hi guys does anyone know what is the best way to do something like when my player goes to the next scene, and wants to go back, he lands back at the position of where he came from? I think I found a tutorial about it but I'm not sure what approach I should go for such as player prefs, scriptable objs and so on
I create a single instance of this in Assets/Resources/SingletonSO and name it GameSounds
Now I can access GameSounds.Instance.someClip from anywhere. The asset is loaded from Resources when I first need it.
I do something similar for a SingletonPrefab class
it instantiates a prefab when I first ask for it
what does your SingletonSO class look like?
you need a stack (something in ram), not persistent storage probably
see the link :p
What does it mean by stack, I'm quite new to this actually.
I use this to bootstrap my whole game. A RuntimeInitializeOnLoadMethod method wakes up the GameController prefab, which DDOL's itself and then loads a bunch of other stuff
I keep seeing YouTube tutorials telling me to use player prefs and so on but now I'm quite confused
That is a bad choice
You should just use DontDestroyOnLoad
Player pref is not good right? I heard it's not safe too
PlayerPrefs is not great in general. It is safe.
But the issue here is reading and writing to and from the disk just for scene change data
So when I do something like Scene manager.load scene then I do don't destroyonload?
I see I see
PlayerPrefs jams all of its data into the windows registry
so writing lots of data will annoy your users
DontDestroyOnLoad is a scene. You add objects to that scene so they persist across scene loads
and yes, there's no reason to use it if you aren't trying to save data between play sessions
Hmm but let's say now I have multiple manager .load scene scripts, I have to do dontdestroyonload for all of em ?
I actually do want to save data at the same time, I also want the player to spawn at the position from the previous level they came from
eg if you go to map A to B to C to D
you push the values to stack posA, posB, posC, posD
when you go back, pop back the value posD, posC, posB, posA, though i think using stack is overkill, you probably wont stack a lots of scene
Ah damn thanks for the tips @fervent furnace @heady iris
I'm still quite confuse but thanks for telling me
A stack is a perfect choice if your scenes form a tree
A -> B and C
B -> D and E
C -> F and G
You can't go in a circle
How do I do that? Do you have any tutorial videos link?
do what?
How do I write the code
yes, but to do what?
All I did during my college years till now was just load scene.blah blah blah
My approach to this was just making multiple scripts for every level
Yikes...
Sounds bad right
That would become complicated so fast
I could understand maybe a scriptable object for each scene but not entire code files
Owh no looks like I messed up π
I have like 5 scenes so far and I used this approach
Imagine after creating 50 levels, you suddenly realise a specific gameobject's (that's in every single scene) structure needs to be changed, and that object is not a prefab
https://youtu.be/UDY0edZZSdo?si=K3x-f-wRUdtEWikb
There's this one video which is exactly what I'm looking for, but should I follow this as I still want to keep my player health and stats when to the next level
Have you been struggling to find a nice way to share some data between your Unity scenes? Using Scriptable Objects, you can have data persist between scene changes. But, there are a few important things to take into account, so stick around until the end.
Note: This isn't a replacement for saving data to a file. This data will only survive in m...
I mean, what does it suggest?
Just when changing scenes, the player spawns at where the user wants to , of course this video doesn't include saving player stats and all that
Saving and Loading systems are quite complex in general
Looking at the topics covered gives me shivers...saving data to carry forward after scene change via scriptable objects? Why not use DDOL
What is ddol?
I need to do more research now damn
In all fairness you could use PlayerPrefs like you said
But that would be super botched
DDOL and AdditiveSceneLoading are what you should research
Not to mention scriptable objects will just reset to values set during build when you close the game
Those managers could just live in their own scene
So you're technically not "saving" anything in grand scheme of things
Alright thanks guys I shall start my journey on ddol and additive scene loading from now on
yes, and abusing them to store data can be very deceptive
when all references to the object are lost, it gets thrown out during a scene change (or when unused assets are unloaded for any other reason)
Wait so if no object is referencing to it and it gets unloaded during runtime it gets reset anyway?
I'm not doung this because I want my imputs all managed in the input system. Makes it easier for ingame keymapping
Yes. Nothing happens to the data on disk
Lmao
but they are managed by the input system
PlayerInput is a component that lets you run methods when input actions are performed/cancelled
So when the "Fire" action is performed, your method runs
You don't care how the "Fire" action actually got triggered. You just respond to it being performed.
Yeah lol and u can't seem to get the syntax for it down hence why I suggested just using the Unith Events
...unless your actions are all things like "E Key" and "F Key", of course, which would completely miss the point of the entire input system
Also Keymapping is never fun to implement if u plan on making a relatively small game I would say it's not even worth it. (NOT TRYING TO DISCOURAGE YOU FROM LEARNING THO)
I need to look into that
I'm trying to spawn a bullet (an Entity with a Physics Body in it), but it spawns into 0,0,0 instead of my player's gun position. (And the bullet doesn't fall with gravity.) Prior to installing Unity Physics (version 1.0.16) and adding the Physics Body component to the bullet prefab, the bullet was spawned correctly into the player's gun position. Why is this?
I jus started unity im confused when i change the scale of an object it doesnt change a green out line apears this never happend before in my previous attempts in learning unity
Show the code
this is a code channel
use this
Alr
So what is the solution for "Prefab Instance problem" Missing with GUID. I removed the prefabs from the project since I didnt need them anymore, but I get those errors on build.
Sounds like you removed some prefabs that are still in use somewhere in your project.
@leaden ice Oh that could be it
it does spawn at where i intended, but it doesn't show up in the right place ingame
these are the packages in my project:
I believe instantiating something instances it at 0,0,0, but you can just change the coordinate on the next line
@leaden ice Ty that worked, Didnt think of that.
because that's the only way I know. For example I can't just do EntityManager.Instantiate(spawnBulletsConfig.bulletPrefabEntity, (float3)localToWorld.ValueRO.Position, ) because can't make it float3
i'm so confused as to what you are doing
using entity component system to instantiate bullets
are you not working with gameobjects?
no, i'm working with entities
Yeah this is definitely ECS code
ok, that's why none of this looks familiar to me
Aren't you passing in the wrong thing to the Localtransform?
it is strange that he would be using the more advanced ECS, but using the more primitive input system
If you want it at the parent position you would just use 0, 0, 0 right?
But you're passing in a world space position
LocalToWorld.valueRO.Position is the thing's world space position IIRC
GunMuzzle is a tag of an Entity that is a child object of the Player Entity, so GunMuzzle Entity's LocalTransform is 0,0,0
sure but you are taking hte position of the LocalToWorld
which is a world space pos
I believe you want Position = float3.zero;
I want it in the GunMuzzle's position (so child's position)
yes and you want it at the same position as the muzzle right?
If so you want this
Should probably be asking in #1062393052863414313 for future reference
well I guess nvm you're not actually spawning it as a child right?
no, i'm not spawning it as a child
it spawned in the correct position before installing the physics addon. suddenly started appearing at 0,0,0 worldspace after installing
Ok then it's probably the physics body doing it yeah
you probably need to set the position of the physics body as well
how big of a deal is it to update the unity editor version of a project? Iβve stayed to the same editor version for almost a year now, but changing to a windows system led to daily crashes for no reason
depends if you want updates?
It's almost always just a few button clicks and some waiting, and sometimes some more manual package updates
i mean how many things tend to break when updating?
occasionally there's some major incompatibility, and the risk of that gets higher the more versions you're jumping ahead
0 in my experience around 90% of the time
welp, wish me luck then lmao
most of what I've been waiting for still prototyping so im still using 2021/2022 stable versions
anyway just make a backup / VCS commit
then do it
and you can always roll back if it goes sideways
i did a commit, and separate ZIP file in case
then don't even think twice
2021 also objectively has the best project load screen currently
Also make sure after you upgrade you immediately make another commit
I always have commits that are just "Upgraded to Unity XXXX.XXfXX"
it is done
and everything looks fine
i donβt trust the whole runtime fee thing, so 2022.3.20f1 is the last version for me, I suppose
what auto generated class is it?
If you click on the action map asset you will find an option to auto generate class for it
It will have the same name as your Input Actions Asset.
Do any 1 know how i can code a inventory system i have a big problem whit that
YouTube "unity inventory system"
From the project area or or in the Input Actions editor? because neither is showing that toggle
it dosent work thats why im asking here
Elaborate
Oh wait inspector Generate C# class?
Yes
Yes the instructions are in the link I shared
Too vague of a question. If you have tried something and ran into trouble, feel free to share what you have and what's going wrong with it.
Just noticed that lol.
playerControls = new PlayerInputs();
thrustInput = playerControls["ThrustControl"].ReadValue<Vector2>();
Is the thrust Input meant to change somehow
Cause it can't index to playerinputs
is it PlayerInputs.thrustcontrol?
oh I got it
π 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 this a few set of questions or is it in reference to the last one? Just askin
i have a moving script but dont know what i need to do so i cna sprint when i hold shift
make the speed higher?
sprinting = Input.GetKey(Keycode.LeftShift)
movespeed = sprinting ? regMoveSpeed : sprintspeed;
but then the speed dose not make it higher
wut
I would recommend you search youtube for a video regarding exactly that. Search for "How to make a player sprint in unity" and "How to use Input System" get an understanding of the basics of those and ask questions of that.
also this is #π»βcode-beginner question
Not to be rude, but the way you are asking seems like you are struggling with the basics of this topic. Which I'd highly recommend you watch videos covering those basics first. Like videos on Unity Velocity, Inputs, etc. Then ask us in #π»βcode-beginner about anything that confused you there. But take time watching it
Talking from experience
i have small problems like in this script i whant so i can sprint but cant seam so i can sprint
first of all configure your IDE
!IDE
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
you got it π
Where is the if statement checking for isrunning = true?
Its not going to run without the logic there for it.
thats why im asking i need help you know
I understand that. I'd recommend going on youtube and getting some coverage. Honestly I would recommend you watch some videos on Unity Input System, a video on Velocities, and work from there.
Not to be rude but looking at the code it feels very shoved together. Like you are making boolean variables for your if statements and then halfware down you forgot about them and put the getkey right into the if statement.
I'd advice firstly moving to Input System with your inputs and making a function for each of your actions.
anyone know a fix?
stop trying to access a null reference
this is a standard NullReferenceException, which is the most common error you will receive in C#
you simply need to identify which thing you tried to access was null, and fix that
either by making it not null before you access it, or by checking if it's null before trying to access it.
also dont crosspost
Sorry Im really new how do I identify which one is null
Using basic debugging tools
okay thanks
such as attaching the debugger, or simply Log statements
anyone who got a parkour controller?
the google
searched but cant find almost nothing,every tutorial doesnt explain a thing and its just a short resumary of what he did
found some sketchy things to download that is supposed to be one but its too off
i almost cringe when i hear "I cant find anything" on google
its a complex thing that how its implemented heavily depends on how you game works and how your world is constructed
best to break it down into smaller steps
work on one part of it at a time
3 hours tutorials π’ im not doing this
then gamedev is not for you
fr
bro 10/11 words he talks about how he made his game,it got nothing to do with the controller π
That's very unfortunate
PlayerInputs playerControls;
private Vector2 thrustInput;
#region Monobehaviour API
private void Start()
{
rb = GetComponent<Rigidbody2D>();
playerControls = new PlayerInputs();
thrustInput = playerControls.Player.ThrustControl.ReadValue<Vector2>();
}
private void Update()
{
float yAxis = thrustInput.y;
float xAxis = thrustInput.x;
Debug.Log(xAxis + yAxis);
ThrustForward(yAxis);
Rotate(transform, xAxis * -rotationSpeed);
//Store ship data for UI
currentVelocity = rb.velocity.magnitude;
currentHeading = rb.rotation;
}
Gotta ask, it seems my y and x Axis are returning 0s no matter what I press. Would this be a setup issue with the action or the location of the readValue thing? Can't seem to figure it out.
Fr
you never called playerControls.Enable();
π€¦
Also thrustInput = playerControls.Player.ThrustControl.ReadValue<Vector2>(); is something that you need to be doing in Update not in Start
As it will change as the game goes on
You can't just read the player input on the first frame and stop!
yeahh was thinking that too. Glad I wasn't insane . Thx
!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.
barely
π 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.
jesus..
lol
look thats a lot of text, (checks notes) its on the 2nd line
no one got attention for that
Would this work?
// using UnityEngine;
public class ParkourController : MonoBehaviour
{
public float jumpForce = 10f;
public float wallRunForce = 5f;
public float wallRunDuration = 1f;
public LayerMask wallLayer;
private CharacterController characterController;
private bool isGrounded;
private bool isWallRunning;
private float wallRunTimer;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
Jump();
WallRun();
}
void Jump()
{
if (Input.GetButtonDown("Jump") && isGrounded)
{
Vector3 jumpVector = Vector3.up * jumpForce;
characterController.Move(jumpVector * Time.deltaTime);
isGrounded = false;
}
}
void WallRun()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.right, out hit, 1f, wallLayer) || Physics.Raycast(transform.position, -transform.right, out hit, 1f, wallLayer))
{
if (!isGrounded && Input.GetButton("Jump"))
{
isWallRunning = true;
wallRunTimer = wallRunDuration;
}
}
if (isWallRunning)
{
Vector3 wallRunForceVector = Vector3.up * wallRunForce;
characterController.Move(wallRunForceVector * Time.deltaTime);
wallRunTimer -= Time.deltaTime;
if (wallRunTimer <= 0)
{
isWallRunning = false;
}
}
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
so will this work?
Dunno. Have you tried it?
@mental rover why are you clown reacting to so many people?
in the character controller?
Ah, I recommend !learn then
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
There's a couple people who are very clearly just trolling the discord at the moment π
Clearly just learning imo. Struggling
I mean eugen is OBVIOUSLY not trolling.
Fedle... maybe, but I don't think so
alot of people do not realize how many steps and work are involved and just kinda get overwhelmed and lose the trail
I'm trying to make coroutines serializable so that I could save and restore their state for game saves and persistent levels. Answers I've found online were either too vague to be of any use or said to move stuff outside of Coroutines to the Update function, which invalidates the entire idea of using coroutines in the first place as a convenient function that can be executed iteratively over time.
I've got here so far, a custom serializable class that will hold ref to the coroutine and execute it, but now I'm stuck, how to actually make use of the yield instructions that the coroutine returns? For example WaitForSeconds stores the seconds m_seconds, but it is internal and therefore cannot be reached from the outside.
public ManualCoroutine(IEnumerator routine, bool paused = false)
{
this.routine = routine;
this.paused = paused;
routine.MoveNext();
if(!paused) Subscribe();
}
private void Subscribe() => GameManagerGlobal.ManualCoroutinesTick += Tick;
private void Unsubscribe() => GameManagerGlobal.ManualCoroutinesTick -= Tick;
internal void Tick()
{
if(!paused || elapsedTime<maxTime)
{
elapsedTime += isFixedTime ? Time.fixedDeltaTime : Time.deltaTime;
if (waitingForSeconds < elapsedTime)
{
if (routine.Current is YieldInstruction route)
{
recordedStep += 1;
if (route is WaitForSeconds wait)
waitingForSeconds = wait.m_Seconds + elapsedTime; // <- where to go from here if this doesn't work?
}
if (!routine.MoveNext())
{
Unsubscribe();
}
}
}
if (elapsedTime>maxTime) Unsubscribe();
}
move stuff outside of Coroutines to the Update function
+1 for that advice, really... coroutines are rather low control fire and forget things... for anything else is just kinda annoying to deal with them
but for the fun of it... what do you wanna do? save a coroutine's state in a file and then continue from where it last was on Load?
if you want to serialize coroutines you're just saving w/e member data they add previously before destroying them, then when deserializing you're just reconstructing the whole thing and appending the databack.
As son as I'd want to start two coroutines this approach will fail
why would it fail?
(also, the more coroutines that control game logic - the sadder (lets call it higher risk of later annoyance, not a strictly bad thing))
Update would probably make it easier though as populating lists would easier than restarting the coroutines
Serialize coroutine should be impossible since you have to capture local variable valuesβ¦.maybe you can use reflection to find out the class generated
the want to Serialize a coroutine is strange to me
Well if I move the, say, WaitForSeconds functionality of routine into an Update, and it's a coroutine that spawns a bomb after 5 seconds, if I trigger StartCoroutine 4 seconds after the first one again, it won't spawn it a second later, it will begin to wait for 5 seconds to elapse again
Why?
the only major difference between coroutines and update is that you can sleep coroutines, but otherwise you can manage everything in a single update
that depends on your logic... if you want to have several of these at the same time, you'll need more state data
A more concrete example, my game uses trigger interface system so that game objects could inbteract with each other. It can include a delay, so you press button and door opens only two seconds later or something. One object can have many targets it can trigger if it itself was activated in a certain fashion. So if I set one othe trigger targets to trigger after 10 seconds, but in this time player leaves the level to an adjacent one and then returns... trigger won't ever be completed, the sequence it was a part of is now broken.
it's a bit more complicated, but you're just serializing flags in that regard
and figuring out where you last left off with those flags
I use an IReadOnly interface to expose getters of some data structure, can C# compiler figure out to inline it?
My previous solution was a class that imitates coroutine functionality through going througs a series of "if" statements and checking if this if's condition is true and its step matches the sequence progress, but it was not an optimal solution because I needed to create a new inheriting class for every new type of "manual coroutine" I needed, and it turned out it cannot use any private or protected variables.
I'd take it back to basics and think in terms of "what data do I need to reconstruct the current state of triggers (and timers)?" rather than trying to serialize the exact state of a coroutine in a general case
You need to be saving your persistent state somewhere, either in a file or a DDOL manager, and loading the data. Its crazy that you say when a player leaves the level and you want to resume coroutines
reconstructing the exact coroutine and its stages is awkward, constructing a new coroutine that simply starts with the remaining time from the last one isn't quite so bad
Also the decoupling of your linked doors is a bad design
what do you mean "decoupling linked doors"?
Sorry, I meant the button and the door. Both of those "linked" items should share the same state to prevent syncing bugs
sorry miseed this, but i feel having this want or need in your project. just means your data and your logic are too tied to eachother
the game state should just be data that can be saved
not where you currently are in a enumerator
especially if you are wanting to leave a level and return it needs to be saved somewhere
if the state is "a door is going to open in 4 seconds", that's something important to save though - though it does sound to me like Darth is overcomplicating trying to serialize a coroutine object itself instead of the raw data of a door opening in 4 seconds
Both of those "linked" items should share the same state to prevent syncing bugs
Uh... I don't quite understand what you're trying to say. I've seen plenty of things in games that happen after a delay from you doing something to trigger them. Cinematics, scripted sequences, puzzles...
especially if you are wanting to leave a level and return it needs to be saved somewhere
Well, that's the edge case I've found. I didn't intended the player to be required to leave level while sequence is playing out, but I've found accidentally that if you do - it breaks.
most games are very deliberate about what they save and do not save, not just wholesale trying to save the state of a whole coroutine object
for instance using basic json:
{"door_one_unlocked": true}
...
scenario:
player press's button => door has a 10 second delay => player leaves before 10 seconds
solution 1: entering the level => just have the door opened already
solution 2: (to maintain the timer) = > save the door value and time remaining in a file or DDOL => upon reentering level, start a new coroutine with that wait time ?
The raw data in this case is "there was a signal to open dor in 4 seconds 2.456 seconds ago". And, again, its a specific simple example, I have more complex coroutines, including those that have, say, several WaitForSeconds yields. How am I supposed to move that to the Update - create a bazillion of timers? And again, how to run two such coroutines simultaneously? The whole system grows in complexity very fast
its fine to repersnet the logic as corroutines or how ever makes sense
the issue people are pointing out is you cna jsut save a whole coroutine
a coroutine is such large moving target to serialize, its state can be effected by pretty much anything in your game at any point in time
and contains logic not data
also say you could do this, and you return to the level? does it just skip to the part of the coroutine you want?
what happens to all the state the coroutine would have modified to get to that point, if it skips it
Ideally, yes, that's what should happen.
and part 2 of my question
if it skips to a point everything before that would not be done
It got saved when I've left the level?
so really you just want a crap load of ifs in your coroutine tracking if flags have been set or not to skip sections
and wait steps that can take in the remaining values
my head hurts just thinking about programming that design
if i had to do it feel like i would use something like the command pattern
something to capture the state, e.g
struct MyTriggerState {
int stage;
float timeRemaining;
int roomId;
int doorId;
}```
you can serialize this, and then have some method on loading a level e.g
```cs
public void RestartTrigger(MyTriggerState state) {
// construct object, init values, start coroutine
}
"A crapload of if's" is how my first attempt at making serializable coroutine went π
[Serializable]
public class CR_Player_Stun : CR_Routine
{
internal float stunTime;
internal override void Update()
{
if (Begin())
{
player.isStunned = true;
InputControl.Instance.SetControlState(ECState.Character_NoMove);
player.meshAnimator.SetBool("Stunned", true);
}
if (WaitForSeconds(stunTime))
{
player.isStunned = false;
}
if(WaitForSeconds(1))
{
if (!player.isStunned)
{
InputControl.Instance.SetControlState(ECState.Character);
player.meshAnimator.SetBool("Stunned", false);
}
Disable();
}
}
}
But that approach has the previously mentioned problems of each coroutine needing to be a new subclass and it being unable to access anything not public from the object that triggers it.
hmm maybe each state changing operation is implemented in a command, and you push them onto a stack
each command has a method for instantly applying and applying over time
waitforseconds is kinda problematic as you do want to be tracking the time yourself if you are to serialize it
like having the exact waits how important is this, feel if it did not happen when loading back getting the full wait agian is fine for how most games work and what players expect
Yeah, the base class had everything to trach and save that for serialization. Update() gets called from Tick(), which subscribes to even in my game manager on the activation of ManualCoroutine, and records how long it was active
private void TryAdvance(bool result)
{
if (result)
{
recordedStep += 1;
elapsedLastStep = elapsedTime;
}
step += 1;
}
/// <summary>
/// <para>Wait for the set amount of seconds.</para>
/// </summary>
internal bool WaitForSeconds(float seconds)
{
bool result = (elapsedTime >= elapsedLastStep + seconds && step == recordedStep);
TryAdvance(result);
return result;
}
thats what we don't know, i mentioned just having the door already open when going back to the level. restarting from the full time would also be fine.
!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.
You just need to reverse this idea - coroutines are a fast and loose state machine that hide the details to make things a bit more syntactically simple for simple cases. You will be better off actually representing the state machine yourself and serialising that.
In regarding my trigger system, my main concern is sequences. I'm going to use my system to create non-cinematic events in my game, kinda like how Half-Life did it, and if player accidentally leaves and returns in the middle of 10-second long "cutscene", it would feel weird if for the first 5 seconds nothing would've been happening.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShoot : MonoBehaviour
{
public Transform playerGunBarrel;
public GameObject Range;
// Start is called before the first frame update
public void Perform()
{
if (Input.GetKey(KeyCode.F))
{
PShoot();
}
}
public void PShoot()
{
//store a reference to the gun barrel.
//instantiate a new bullet.
GameObject bullet = GameObject.Instantiate(Resources.Load("Prefabs/Bullet") as GameObject, playerGunBarrel.position, Range.transform.rotation);
//calculate the direction to the player.
Vector3 shootDirection = (Range.transform.position - playerGunBarrel.transform.position).normalized;
//add force to rigidbody of the bullet.
bullet.GetComponent<Rigidbody>().velocity = Quaternion.AngleAxis(Random.Range(-3f,3f),Vector3.up) * shootDirection * 150;
Debug.Log("Shoot");
}
// Update is called once per frame
}
Anyone know a way I can "Slow down" the Input.GetKey function so that the bullets don't come out of the gun every frame the key is held down?
notice how this is exactly what would happen if you saved and loaded mid scripted action in half-life though
tracking all of that over a whole game is alot
if the player left from a level and went back, most people do not want to go back through a cut scene, start the player at the next step
well difference between saving steps and wanting to save the progress of 1 step
it feels like a step is too large
sounds like to me , create a database design for state management for all your cut scenes
like the half-life example, generally 1 scripted sequence is triggered by where the player currently is, or by the end of the previous scripted thing
thus if you save mid thing, and load it will replay it
but if you save and reload after a step you are fine
so feels like smaller coroutines, and at the end of one you save a flag, so something else can see that flag change and start its stuff
Something like that maybe?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShoot : MonoBehaviour
{
public Transform playerGunBarrel;
public GameObject Range;
private float firerate = 0.7f // the rate of your fire in seconds between shots;
private float lastFireTime =0;
// Start is called before the first frame update
public void Perform()
{
if (Input.GetKey(KeyCode.F))
{
PShoot();
}
}
public void PShoot()
{
if (lastfiretime > firerate)
{
lastfiretime = 0;
//store a reference to the gun barrel.
//instantiate a new bullet.
GameObject bullet = GameObject.Instantiate(Resources.Load("Prefabs/Bullet") as GameObject, playerGunBarrel.position, Range.transform.rotation);
//calculate the direction to the player.
Vector3 shootDirection = (Range.transform.position - playerGunBarrel.transform.position).normalized;
//add force to rigidbody of the bullet.
bullet.GetComponent<Rigidbody>().velocity = Quaternion.AngleAxis(Random.Range(-3f,3f),Vector3.up) * shootDirection * 150;
Debug.Log("Shoot");
}
lastfiretime += Time.deltaTime
}
// Update is called once per frame
}
Resources.Load every time you shoot
You can just drag the bullet into a GameObject field, which is both better and let's you plug in different prefabs for different instances of the script
that on top of no pooling lol
Better yet is to use pooling system.
Pooling isnt needed 100% of the time. Sometimes it can be more of a hassle
it worked! thanks!
also how to properly reference assets should come first
why is my world space ui not interactive when im using a output texture on my camera?
What did you do to make it interactive?
i made a button
Ok
And?
Do you have the button set up with the OnClick callback?
did you use ScreenSpace - Camera?
yes
Do you have an event system in the scene?
What code does the onclick method link to?
Gonna need more info provided instead of dragging it out of you πΈ
im using a raw image over the screen to make a pixelated look. and when i take the output texture to none, it works
but not when i use the render texture
it just debugs
imo this is a bad way to do cause it creates more issues then helps with, just use a pixelated shader lol
i guess
yeah thats a flop nvm
I just got around this ages ago by just using pixel shaders and stop doing the RT thing
Why am I getting a Json parse error here?
https://pastebin.com/Hpj8zX9G
As you can see on the log, it is getting the correct path to the json, so I don't know what is wrong?
It is also impossible to be the wrong type, as I'm serializing WorldData
This is how I am serializing
https://pastebin.com/Wcd1Bdbj
paste the json
Json is probably messed up
try with a non-empty name
K, just a sec
print the json
@rigid island βοΈ
is that the file though or what the method is getting ?
i'd imagine that's the content of the file
Even with non-empty name, still same error
Your debug is also after the parse, print the name beforehand
thats the file
I think you may be looking at the wrong file
it is before
print whats happening in the code
The first link you've shown has the debug at the end of the for loop
also paste/post your World data struct
Wait, ToJson don't serialize lists?
it should
If the data types from the list are serializable, then yes, ToJson serialize it.
WorldData is Serializable yes?
Is your function getting the right JSON string value?
maybe cause its a prop ?
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.
It is
oh
i see your problem
you're trying to deserialize the path of the file, not the contents
oh
it does not support hashset
string[] worlds = Directory.GetFiles(Application.persistentDataPath, "world_*", SearchOption.AllDirectories);
WorldData worldData = JsonUtility.FromJson<WorldData>(worlds[i]);
Nice
what you want is probably more like this:
List<string> worldFilenames = Directory.GetFiles( blah bla blah );
foreach (string filename in worldFilenames)
{
string content = File.ReadAllContent(filename);
WorldData world = JsonUtility.FromJson<WorldData)(content);
}
Oh than thats a problem
π
so i normaly do not use JsonUtil since its pretty limited in types and features
but types wise its all the same stuff you can show in the inspector
so you can use that as a quick way to test
yeah but proly fine for code-general/beginner.. but yes, later on you're gonna wanna use NewtonSoft or another "real" json parser
It worked.
or go πͺ and use MessagePack
hell even the microsoft one supports more
π
Yeah, gonna change to NewtonSoft
I'll have to serialize dictionaries later anyways
I hope newtonsoft can do it?
yup
yup
That's great, thanks for the help guys
if it did not i would be screwed got lots of dicts in my save logic
the whole unity UGS save systems would go in the shitter!
funny enough I knew it was using newtonsoft when i got a Self referencing loop detected error from trying to use Vector3 in the Unity Cloud Save
yeah have to override a few things to play nice with unity
nicee! iirc you just had to disable some setting it was like an option thing, but yeah sadly that only works for your client side .
the one unity uses for Cloud Save is on their server so this cant be done on their end
since for Cloud Save you have to send a Dictionary it uses json.net on the server side to serialize it
yeah never used cloud save
always used our own binary formats for saves, and in some projects playfab
hey everyone i had a rotation script that i know works but i cant get the gem to rotate any help?
help with what, there is not enough info
start by sharing the script
ive put the script onto the gem but cant get it to rotate in game
public class RotateScript : MonoBehaviour
{
//Rotational Speed
public float speed = 0f;
//Forward Direction
public bool ForwardX = false;
public bool ForwardY = false;
public bool ForwardZ = false;
//Reverse Direction
public bool ReverseX = false;
public bool ReverseY = false;
public bool ReverseZ = false;
void Update ()
{
//Forward Direction
if(ForwardX == true)
{
transform.Rotate(Time.deltaTime * speed, 0, 0, Space.Self);
}
if(ForwardY == true)
{
transform.Rotate(0, Time.deltaTime * speed, 0, Space.Self);
}
if(ForwardZ == true)
{
transform.Rotate(0, 0, Time.deltaTime * speed, Space.Self);
}
//Reverse Direction
if(ReverseX == true)
{
transform.Rotate(-Time.deltaTime * speed, 0, 0, Space.Self);
}
if(ReverseY == true)
{
transform.Rotate(0, -Time.deltaTime * speed, 0, Space.Self);
}
if(ReverseZ == true)
{
transform.Rotate(0, 0, -Time.deltaTime * speed, Space.Self);
}
}
}
ok and you have no bools checked in the screenshot you posted @ripe mountain
also next time post !code as follows β¬
π 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.
[SerializeField] UnityEvent lights; //I want the option to click the + button and add the amount of lights I need per thing I'm doing
[Header("Timers")]
public float timer;
public float minTimer;
public float maxTimer;
void Start(){
timer = Random.Range(minTimer, maxTimer);
}
void Update()
{
FlickerLight();
}
void FlickerLight()
{
if (timer > 0)
{
timer -= Time.deltaTime;
}
if (timer <= 0)
{
//How can I make it so the amount of lights I have added get enabled / disabled here?
timer = Random.Range(minTimer, maxTimer);
}
}
}
Hey everyone. I made a script where at the start I had 4 gameobjects which were lights and they all either turned on / off depending on the timer, but recently I have been needing more in one script but I don't want to add loads of gameobjects so I found the UnityEvent where I can then press the + button and add the amount I need but doing that means the light.enabled = !light.enabled didn't work anymore. What can I replace that bit of the code with instead?
why not just put the lights inside an array ?
[SerializeField] Light[] lights;
void ToggleLights()
{
for (int i = 0; i < lights.Length; i++)
{
lights[i].enabled = !lights[i].enabled;
}
}```
I didn't actually think of that
That work great. This was the way I was thinking of but I think I started googling down the wrong path! Thanks alot!
Anyone got a good tutorial on UI like more advanced stuff like a back/ previous button and stuff
back / previous from what?
Like a back button
back to where?
It's just annoying and confusing enabling and disabling ui elements
The functionality for going back has nothing really to do with UI. The UI side is as basic as it gets: a button that calls a function.
No I know. It's a design thing but I was wondering if someone like had a good system and stuff
None I can recommend. Just what I do, use a bunch of subcanvases and turn them on and off based on some controller managing the state of the menus.
Anyone have any ideas on going about making a fighting game?
Specifically the motion inputs
wdym the motion inputs
this question is as vague af
Still no clue what you're talking about. Try using more common words. Not everyone here has a grasp of fighting games vocabulary.
Can somebody help me identify why Unity freezes indefinitely whenever I enter playmode after this code is ran?
/// <summary>
/// Create a new entity instance managed by the object pool.
/// </summary>
public static Entity Precache(ID id)
{
// Create instance.
Entity source = Resources.Get(id);
Entity instance = Object.Instantiate(source);
// Pool instance.
Mark(instance);
// Output instance.
return instance;
}
Once the entity is instantiated, the freeze occurs, but only if a serialized bool property is false on the entity component. Keep in mind, the bool has no references besides the declaration in the entity class.
How is this object spawned? Is it possible an object is spawning itself over and over
It's a simple for loop called in start.
and what script do you have on those
I've only attached my entity script which essentially stores meta data, it doesn't do anything in particular.
All assigned in inspector btw
This is very vague, check to see if what I said above is happening. Likely an object spawns itself which spawns itself which...
Also attach the debugger so you can go through your code line by line and not freeze your unity uncontrollably
Looking through my git commits, the bool recently changed on the commit that I thought caused it, but this issue appears to be far older than I realized. I'll come back with some more info if I'm still having trouble.
And I thought I was going crazy by how little the changes should've impacted my project.
if swapping a bool causes ur game to freeze, you should really fix that
My bad. I'll try to make it simpler to understand next time
Is there a way I can use a raycast that rotates direction instead, like, is there a sort of plane cast I can use so I can make it really tall?
Like boxcast?
is there a way i could cycle through all the items in "GameInputs" with an index? for example GameInputs[0] would be select one and so forth (in the input system)
You can make an array of InputActionReference
This type lets you serialize a reference to an input action (surprise!)
oh alright thats good to know! Ill give it a try
thanks for the help! been looking for something like this for a whiel
Yeah, it's really nice. I use it for basically everything.
I just wish there was an InputActionMapReference, too..
the comments for InputActionReference mention wanting to implement that
yeah that would be nice
How can I make a boxcast spin? I want the direction to spin clockwise on the y-axis. Currently I am trying to add 1 to the directions y value every frame, but that changes the position of the end of the boxcast.
You want it to spin while moving forward? π€
no
I want the raycast to spin similar to how a radar scanner's soundwaves spin
that line, spinnning
https://docs.unity3d.com/ScriptReference/Physics.BoxCast.html
Check the params
would use a regular raycast every frame
A cast takes a direction and length, that's all. So create a direction, and rotate it every frame and boxcast with that direction.
WIth a regular raycast I have to worry about the y position of the player
technically you can use a spherecast here and check a set angle/direction
sphere or box is fine too
but you are firing them off each frame rotationed a bit more
What Mao said lol, whoops
or overlapsphere actually
right overlap
for the whole radius and just calcualte the angles of everything caught
That is what I was using before. Would I just need to somehow make animations for it?
well you are talking about the logic part
well, I was using overlapcapsule
I was thinking I could redesign the logic to match the visual
but that would probably work too
that would cost much more
much easier to get everything, calculate the angles then do the visuals with that information
as the visual part of it is rotating, you would know its angle, and can use that to figure out from your objects which ones are udner it in that point in time
Is VS ignoring self made Snippets, basically randomly, a known issue?
Hi team
I am looking to Object Pool my projectiles. I will have different types of projectiles, so many pools.
I have a scriptable object for each type of projectile, with the prefab, etc
I want to have a Global Object Pooler singleton
that all the projectile stats SOs add themselves to a list on Awake, and then on Start, the global object pooler will go through all of them, and count how many of each projectile there is
based on that number, it will create a pool for each projectile and make the max amount of pooled objects based on how many weapons for that projectile there are.
The only issue I have it,
I need to dynamically create all these object pools.
So as far as I`m aware, C# doesn't let you create variables from a string or anything like that, aka "objectpool name = new object pool" where "name = weaponstats.prefab.name"
So am I stuck with just making individual object pools for each instance of the weapon?
because that's where I can make these variables in advance. I'll have potentially many multiples of the same pool, instead of one big one. Seems like a waste.
Anyone have a suggestion?
I hope this makes sense.
Hey, I'm not sure if this belongs here of the beginner channel, but I figured I'd ask: is it good to have most of the meat of the game be in one script in an attempt to avoid spaghetti code? Right now that's what I'm doing and I'm not sure if it's a good idea. Thankfully my game is still in its very early stages so there's plenty of time to fix it if needed.
I ask this because my earlier attempts at making a game in Unity were plagued by spaghetti code, and I'd like to try and avoid it for this project.
Usually it's the other way around. Avoid spaghetti by dividing up your scripts.
Okay, so instead of having my main currency manager, shop manager, and stat manager in one script, I should have them each in their own scripts?
I'm just trying to make sure if I understand this right.
Unity kinda forces you to use separate scripts anyway if you've got multiple non-nested classes in a single script because it's ambiguous to the editor when assigning stuff on it.
For anything that derives from mono that is.
Okay. My only problem is that I'd have to probably singleton them because of the nature of the copper needed to buy things from the shop and increasing stats. Then again, if I have to, I guess a few singletons wouldn't hurt too much. I just don't want to overdo it like my other previous projects.
another important question is whether or not it matters if it's spaghetti code in your particular case. in my experience, planning for infinite expansion of code is just unrealistic, and if you are making a relatively simple game, I would just go with what works. I do think you should split things up somewhat, but don't split it up too much until you actually know why you are splitting it up (as in, you run into a tangible issue or have some reason to split it further). The "manager" approach usually is spaghetti code, but it may not matter much in the long run if the game functions
definitely better than having the whole game in one file though
That is true. I'll try splitting them up and see how far that goes. Like I said, my game is in its very early stages so far, so it shouldn't be too hard to fix this problem.
many published games have a lot of singletons set up as you described above
You can always add secondary layers to your singletons to decouple them a bit more (service locator patterns), but beyond something like a GameManager, there's always ways to bind and find those references.
i.e, if GameManager has an AudioManager reference, you don't need to make AudioManager a singleton since you can simply reference GameManager.
I want to make an explosion like particle but dont know how to call it with code so it happens at certain given time and i cant manage to find any video that says how, does anyone know how to do it?
you mean a timer?
https://docs.unity3d.com/ScriptReference/ParticleSystem.Play.html
maybe you want this? not fully sure what part you are having issues with
i want to make a particle system pop up whenever i kill an gameobject
but i dont know how to call that function with code and cant find anything related
might want call ps.Emit() each time
so i should create a variable called particle system and then whenever i want to call it write ps.emit() ?
or well it would be particleSystem.emit?
no clue what all that means
just call the method
english is not my main language and its kinda hard to understand
how do i do that?
and how can i make it produce no particles until i call it
Ohhhhh
true
ty!
ill try it
can i ping if it somehow doesnt work?
@rigid island so its not a code issue since im making the particle itself first
how do i make the particles take a certain colour?
more than take, the word im looking for is "be"
nvm it seemed to solve itself alone
i had the start color part set to a red-ish but it came out as purple, restarted and now it works
epic
@rigid island i have a code issue now
xD
since i trigger it when the game object has a float set to 0 (the float is the amount of hp) it instantly deletes afterwards
so what i thougt on doing was making the sprite invisible and remove the collider ( so it cant take any hp from the player) and once the particle system ended doing 1 cycle destroying the gameobject
how can i change the sprite to none?
here is a ss of what i have atm
ignore the variables that arent showing in the ss
You can just set the enabled state of the spriterenderer to false
ohhh
and how can i make it to wait until 1 particle cycle ends?
with a ienumerator?
havent used one in a while but i think i remember how they work
what was a method again?
if you can ping me in case you still here whenever you answer it would be nice (since im multitasking and trying to mess with whatever im doing in the code)
oh i messed up big
i feel professional now that i setup github lol
its actually incredibly easy
download a program, login to github, 4 or 5 lines of code and its on github
In this step-by-step tutorial, learn how to use Git and GitHub for source control management (SCM). We start with Git. What is it? How you can get it running on your system, and how you can start working with it? Then we look at GitHub.com, a platform for hosting and collaborating on Git repositories. By the end of this video, you'll be well on...
roblox head over here explains it well
amazing
bro roasted him for free
how can i record my screen ?
haha his head looks like its about to get put on a stick and roasted loll
snipping tool
bro seems like he can sprint and jump while holding (idk how much but a big number) of golden block apple stacks
amazing
lol
is it more efficient to send my github link if an issue could be anywhere in the project?
TRIGGER WARNING(my friend screaming like a chimp)
so the think is that idk how or why
but it does more than 1 cycle and more than 3-5 "particles" per cycle
im gonna be honest i really dont feel like it haha
np
it makes total sense
that would be the point of setting up github
im just checking if someone would help me
Solved it. My bullet consisted of an empty parent GameObject with a Physics Body and Physics Shape in it, plus a capsule child GameObject for visuals. I found out that the capsule had a Capsule Collider component attached to it, which somehow broke things. I removed the component and now the bullet spawns in the right location (sorry this isn't a code related problem anymore, but it's solved now )
How do i get rid of this message?
Looks like a bug in the entities package. I would make sure it's up to date, and re-open the Entities Hierarchy
I was about to say "make it not null" but then I read the source and went "oh shit wtf?"
im trying to basically delete a repository and start from scratch using git. how can i remove the repository without risking deleting the entire folder on my local drive
** SOLVED solution in code block**can someone tell me why this function is not working? i feel like its a very small issue. all tiles seem to be disappearing at the same time and i want to stagger them with the while loop. wait for those to finish and then destroy all of them to make room for new ones.
here is the code:
public async Task UnloadLevel()
{
List<Task> tasks = new();
pointDictionary = new();
float elap = 0f;
int count = 0;
tasks.Add(levelTiles.transform.GetChild(0).GetComponent<TileElement>().GrowShrink(false));
count++;
while (elap < 1f)
{
elap += Time.deltaTime / 1f;
if (elap >= 1f)
{
tasks.Add(levelTiles.transform.GetChild(count).GetComponent<TileElement>().GrowShrink(false));
elap = 0f;
count++;
}
if (count >= levelTiles.transform.childCount) break;
await Task.Yield(); <-------- I FORGOT THIS LINE!!!!!!
}
await Task.WhenAll(tasks);
while (levelTiles.transform.childCount != 0)
{
Destroy(levelTiles.transform.GetChild(0).gameObject);
await Task.Yield();
}
}
What's the goal, do you just want to erase all the past history (commits, branches, etc) without affecting the local files?
yea, i got confused and committed the entire project folder instead of just the asset folder. Im not sure exactly which set of folders i need to store in the repository
and i dont know if ive pushed it or whatever, its not showing anything in github, but git status doesnt show anythiung
Easiest way is to just checkout a new orphan branch with git checkout --orphan new-branch-name (or do it with UI if you are using a git UI client), that branch will have no history at all and you can start fresh.
After you are satisfied, you can go delete the old branches. Or revert back to the old branches if you regret it or something.
Good time to make sure you have a proper .gitignore setup this time around, you can use https://github.com/github/gitignore/blob/main/Unity.gitignore as a starting point.
yea im settin it up now
what folders are necessary for unity ?
im guessing just the assets?
That gitignore template tells you which ones are necessary π
Just copy pasting the template should work for most projects.
I mean yes you can, but creating an orphan branch is easiest and you have the option of going back to the old branches so you won't run the risk of messing things up and losing all your progress.
Unless you are talking about GitHub repo not a git repo.
github repo
but i honestly dont care about either, im not tied to whatever i did in git so far.
But you do care about the actual files right? And git/GitHub ensures you won't lose your progress.
yes 0,0
i really dont like how easy it is to delete everything XD
okay so ill do what u said,
Here's what I would do:
- Remove the GitHub remote from your git repo.
- Create a new orphan branch, fix up your gitignore, commit.
- Create a new GitHub repo, add it as the remote.
- Push only the new orphan branch.
- Now you are safe to delete the old GitHub repo, and the old branches.
At any point in time during this process if you mess up/regret it, you still have the old branches/old GitHub repo to ensure none of your work would be lost.
remove github remote?
Yeah so you won't accidentally push to the old GitHub repo anymore because you are going to remove the old repo later anyways.
oh my brain hurts, this is probably an easy problem but ive been at it since 6
would git remote rm destination work?
Yeah that's the command.
yes yes it is
now if i could just edit the .ignore file and commit that to github thatd take out some unnecessary work
but why didnt it show any files in Github if i committed and pushed it?
Create an orphan branch first, then do the edits and commit.
Well, you should be in the branch you want to commit to.
im guessing thats the new one
or even better, if i could untrack all the files except the ones i need
i dont mean to talk your eyes off, just talkin out loud
Creating an orphan branch, fix up your gitignore, and you can just add everything as staged.
The purpose of gitignore is so that the things you ignore will not be tracked, so you don't need to painstakingly hand pick which files to stage every time.
okay, ill get back to u when i get some progress done
alrighty so i made the orphan branch, pulled a unity premade ignore file, saved it, ran commit in the new branch, and it loaded much faster this time. it seems to work out correctly
now all i have to do is push git branch -M master and ill be golden?
Yeah, remember to make a new GitHub repo and add that as the remote, since you said you don't want the old repo anymore.
i dont mind using the same one, are u refering to git remote add origin https:...etc?
In that case yeah, you can just add it back and push.
what does -u mean in push -u origin master?
im sorry im anoying myself, so many questions lol
i used git push origin master and now its taking much longer 0.o
Well it actually has to upload your committed files to GitHub, so that will take a while if your project is big.
yea, beforehand, when i got the errors, it was much faster. it looks like it might take an hour when before it was 10 minutes
You are pretty much done after uploading anyways, just need to double check if you have committed/pushed all the files, and once you are satisfied you are free to delete the old branches both locally and on the remote in GitHub.
okay, hopefully this time something pops up in github
How come my list of strings and list of (serializable) structs are not seriazlized but the list of objects is serialized
When I restart the program, the data in the list of strings and struct are lose
why does this dubble the letters? hello = hheelllloo?
are you saving as u are typing?
are you editing the word as you are typuing
omg
ARE YOU EDITING THE STRING AS IT IS BEING LOOPED OVER
my goodness lol
ohhh
are you editing the variable as it is being looped over?
where
below textComponent
debug.log(textComponent.text)?
Print the typingTextString variabel before the foreach statament.
What did it print in the console?
print out each letter as u are adding it
let me check
it prints two times so its somthing wrong
So your problem lies elsewhere
You've started the coroutine twice
I think the string just has duplicates
If the log prints twice that means the coroutine has been started twice
Remove the = new(); maybe? Unity might be recreating the collections.
likely this too
Ah misread what he wrote. Thought the string had duplicates but instead it's being printed twice - you're right.
will try
nope, didnt worjk
Did you properly setup gitignore? Because Library/ folder should not be committed and the gitignore template I gave you earlier ignores that folder.
yea it didnt include .gitignore, i added it, but my dumbass didnt commit it, i just pushed it.
look up git basic ignbore files
i got a file for it already
I gave them that already.
i assumed the file was already added after saving the document text. I forgot after its modified it needs to be added back
Look at your local commit and check what files got included in the commit, it sounds like you messed up and committed all Library/ and other stuffs too.
yea gitignore itself was ignored
I'm trying to make an "unlit" or "textured" mode and was wondering how I can achieve this? I have this so far
public class UnlitLitTest : MonoBehaviour
{
public bool unlit;
public AmbientMode originalMode;
public void Awake()
{
originalMode = RenderSettings.ambientMode;
}
public void Update()
{
RenderSettings.ambientMode = unlit ? AmbientMode.Flat : originalMode;
}
}
But when it goes flat it becomes suuper dark. I'm trying to achieve what the scene view gives when you disable lighting. Any suggestions?
I can change the ambientLight colour but my concern is that if I cache the original value in a variable it'll change between areas and then the ambient light will be wrong when going back
The component is on two objects or twice on one object
oh my god im so dumb thanks
or since the method is public there's a small chance it's being called from somewhere else
Why is the list of strings not being sereialized?
after game engine restarts, all data in list is gone
How are you populating the data?
Yes but how, are you doing it via script or manually typing in inspector. If via script you might have to do that set dirty stuff
so essentially, user adds objects to list in editor, then for each object guid is created
Yea I think you need to set it dirty then. Theres a pin about persisting changes in #βοΈβeditor-extensions
does this explain why the list of objects is saved but the strings isnt?
Those objects are added via inspector arent they?
yes
Yea then those save the same as if you modify a value on a component. It's different when setting it via script
I see thanks
It works thanks!!
Does anyone know of a good functioning car controller that is free? The one I have allows the car to flip no matter what I do
I've gotten everything else working. My player can walk around my player can get into the vehicle It locks the player into the vehicle and they can drive around but my vehicle tips
You are unlikely to find one that's exactly what you want, especially if we are talking about free anything.
There is always a good way to get a good car controller script that's exactly what you need. Make one
That's what I've been doing. I've been modifying the current car controller script that I have that was a free asset and I've got it where I want it but no matter what I do to the wheel colliders I just cannot keep the car from tipping
Modifying one will probably be more tedious then just making your own. If this is a rigidbody with no constraints, it is free to rotate however it wishes.