#archived-code-general
1 messages Β· Page 123 of 1
Dont know why
You need to use Matrix4x4.MultiplyPoint3x4 after.
With the inverse if I am correct.
Hi. Does anyone know if there's a way to like set default parameters for a public void please? Like, so I don't have to send all those if they aren't needed, like so I don't have to write "null" or something like that for each one that isn't needed
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I would have used your code to give an example.
However, you made a screenshot, and now I cant π¦
oh my bad sorry
public void SendStuff(string TriggerName, float Float, string String, uint Uint, bool Bool, int Int, Vector3 vector3, Vector3 SecondVector3)
{
SendTriggerServerRpc(TriggerName, Float, String, Uint, Bool, Int, vector3, SecondVector3);
}
like that?
public void SendStuff(string TriggerName = "", float Float = 0.0f, string String = "", uint Uint = 0, bool Bool = true, int Int = 0, Vector3 vector3 = Vector3.zero, Vector3 SecondVector3 = Vector3.zero)
{
SendTriggerServerRpc(TriggerName, Float, String, Uint, Bool, Int, vector3, SecondVector3);
}
okay thank you so much
the Bool=true or =false
fix.
and why am I getting an error with the vectors please?
Retry with the version I fixed
error likes "the parameters must be compile time constant"?
yeah
then you may consider function overloading
try default(Vector3)
i forgot the default operator..
public void SendStuff(string TriggerName = "", float Float = 0.0f, string String = "", uint Uint = 0, bool Bool = true, int Int = 0, Vector3 vector3 = default(Vector3), Vector3 SecondVector3 = default(Vector3))
{
SendTriggerServerRpc(TriggerName, Float, String, Uint, Bool, Int, vector3, SecondVector3);
}
okay that solves the error, thanks π
The fact that this method has that much parameters with a lot of different types tell me that you're using this to pass anything, that's pretty bad
The name parameter is even worst.
You could have a single parameter of type object, or use overloads
Oh god yeah I just realised the method name "Send Stuff" definitely a do-it-all method! Shitcode alert!!!
On the receiving side of the RPC they probably have a huge switch statement that switches on the first argument, and uses the other parameters as needed, discards others
tbh I was using that because that was the only fast way to make it possible to use with visual scripting, but now that I'm trying to move everything into C# (because visual scripting just forgot all the references and nothing works anymore), I am a bit lost sorryπ , but yeah you are right about that
You can look into what's called "method overloads", which allow you to have multiple methods with the same name, as long as their parameter types are different
So you could have one that takes in a string, another a vector, another a float, etc.
That worked, thank you π
Making a big game needs: plans and members
every member should do a thing
for example a member should do the coding member should do maps members should do 3d models and a member should do english typing or etc language? isnt that true?
Is it a question ?
yep
@vital bay Don't cross-post. And is this a question even?
public void Bays(bool IsOpen)
{
BaysServer(IsOpen);
}
[ServerRpc(RequireOwnership = false)]
public void BaysServer(bool IsOpen)
{
if (IsServer)
{
BaysClient(IsOpen);
}
}
[ClientRpc]
public void BaysClient(bool IsOpen)
{
//DoSomething
}
Would there be a better way to do this please? Like a shorter way maybe? Or like a way to use that thing of method overflowing to be able to send different types of info for both the server and the client please?
dam it i know the rules but im just dumb eh i aint dumb but i know coding eh... ik dumb questions i aint asking dumb questions but i just gotta say sorry so ig sorry
hey, i posted this yesterday about an issue where if i spam the jump button quickly enough, my grounding check returns true a split second after my first jump, causing the number of jumps counter to reset (giving me a triple jump instead of a double jump)
one of the suggestions i got was to add a jump cooldown that ensures that you can't jump within 0.2 seconds of a previous jump but that hasn't solved the error. i've also tried decreasing the height of my grounding check box and ive also tried implementing a bool that prevents jumping for a short period of time after the jump button is pressed
none of these have stopped the issue and im losing my mind hehe. any more suggestions on how to stop this?
Putting a time is the best way to go as far as I know.
i added these two floats. jumpCooldownCounter measures the time since the last jump plus the jumpCooldownMax value
and then when the jump key is pressed, i basically see if the current time is 0.3 greater than the last jump time
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
private float jumpCooldownCounter = 0f;
private float jumpCooldownMax = 0.3f;
public void OnJumpInput(InputAction.CallbackContext ctx)
{
if (ctx.started && Time.time > jumpCooldownCounter)
{
jumpCooldownCounter = Time.time + jumpCooldownMax;
JumpPressed = true;
jumpInputStartTime = Time.time;
}
if (ctx.canceled)
{
JumpCancelled = true;
}
}
either of these options will work or sure. post the full code so everyone can see to help . . .
maybe it's a dumb question, but what does the jumpCancelled variable do exactly? Because maybe that could be the problem
right now it doesn't do anything but it'll be used to allow the player to release the jump key early for a shorter jump
the issue is definitely the grounding check. there's like a single frame after jumping where the grounding box is still touching the ground which resets the number of jumps
This is kinda strange the way you have done it. Usually, I do everything in an Update loop.
this isn't strange. they're using events with the new input system . . .
Exaclty, when is the event actually being done ? Before or after the ground check ?
This is what I find disturbing.
I actually need to ask this question.
Oh, and I never used the new input system, just to be clear.
I'm using rewired.
the event is invoked when the button is pressed or held (depedns how they set it up) . . .
Which is when in relation to the update loop.
After the update or before.
It can matter.
Inputs from the events usually happen before the updates in the next frame
im not actually initiating the jump from the event itself though
jumpInput = player.InputHandler.JumpPressed;
if (jumpInput && player.JumpState.CanJump())
{
stateMachine.ChangeState(player.JumpState);
}
i have this in an Update() function of my grounded state which takes a jump input from the user and then changes to a jump state
so while the actual jump press may be taking place before the update loop, i only actually check to see if the press should be used during the update loop
share the entire script that handles player movement.
its a state machine so it's all kinda split up. i'll post everything relevant to jumping
here's the relevant bits of code
Grounding Check in the Player class
public bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}```
Update loop in the GroundedState class
```cs
public override void StateUpdate()
{
base.StateUpdate();
xInput = player.InputHandler.NormalInputX;
jumpInput = player.InputHandler.JumpPressed;
if (jumpInput && player.JumpState.CanJump())
{
stateMachine.ChangeState(player.JumpState);
}
}
public class PlayerJumpState : PlayerActivationState
{
private int jumpsLeft;
public PlayerJumpState(Player player, PlayerStateMachine stateMachine, PlayerData playerData) : base(player, stateMachine, playerData)
{
jumpsLeft = playerData.numOfJumps;
}
public override void Enter()
{
base.Enter();
player.InputHandler.JumpInputUsed();
player.MoveY(playerData.jumpHeight);
abilityCompleted = true;
DecreaseJumpsLeft();
Debug.Log(jumpsLeft);
}
public override void StateFixedUpdate()
{
base.StateFixedUpdate();
}
public bool CanJump()
{
if (jumpsLeft > 0)
{
return true;
}
return false;
}
public void ResetJumpsLeft() => jumpsLeft = playerData.numOfJumps;
public void DecreaseJumpsLeft() => jumpsLeft = jumpsLeft--;
}```
Input Handler
private void Update()
{
CheckJumpInputHoldTime();
}
public void OnJumpInput(InputAction.CallbackContext ctx)
{
if (ctx.started && Time.time > jumpCooldownCounter)
{
jumpCooldownCounter = Time.time + jumpCooldownMax;
JumpPressed = true;
jumpInputStartTime = Time.time;
}
if (ctx.canceled)
{
JumpCancelled = true;
}
}
private void CheckJumpInputHoldTime()
{
if (Time.time >= jumpInputStartTime + inputHoldTime)
{
JumpPressed = false;
}
}
public void JumpInputUsed()
{
JumpPressed = false;
}```
Your issue is your ground check. You must also check if you have jump recently.
check if ive jumped recently in the ground check?
well i have that in the input handler. is there a difference if i put it in the actual grounding check?
Otherwise, you will instantiously be consider grounded (Jump has finish)
the "Time.time > jumpCooldownCounter" means that i'm not taking any jump input if the jump key is pressed <0.2 seconds after already pressing it
I mean, you said your error was that IsGrounded was true after you jumped for a split second.
Reseting your whole jump counter
yeah but im not sure what the difference is between putting the cooldown counter in the input handler and putting it in the grounding check. i can try it though
I do not have the whole code and I cannot test. So I do not know exactly either.
However, it is gonna cause issue down the line.
so you think something like this might work?
public bool IsGrounded()
{
if (Time.time < InputHandler.jumpCooldownCounter)
{
return false;
}
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}```
jumpInputStartTime
with a 0.1f
or something small
public bool IsGrounded()
{
return Time.time > jumpInputStartTime + 0.1f && Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
ill see if i can cause the bug again
wait no.
yeah hehe something's gone wrong. it's not deducting jumps now.
i think its the < symbol
nope not that
I do not know, but you definitly need the concept of if you jumped recently in your ground check.
agh goddamnit. ok i accidentally pressed backspace in a different class. that's what was causing the not deducting jump thing. ok. now i'll try the grounding stuff properly
public bool JumpedRecently => Time.time < startJump + 0.1f;
public bool IsGrounded()
{
return !JumpedRecently && Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
still getting triple jumps with this
I do not know them, your code is kinda spread out. Use logs and breakpoint and you gonna figure it out.
yeah. i might just need to throw in a bunch of breakpoints to see exactly why its returning true for the grounding check
how do i save a character's transform to another scene?
You can use DontDestroyOnLoad if it is a persistent object.
do i need a main scene to parent both scenes or no?
The Transform is a component. You'll need to save the game object too if you're wanting the Transform.
Also, what do you mean by save? Transfer the object to the next scene or just copy the position, rotation and scale?
the former
You could probably flag the object DDOL then move it to the next scene after the scene has loaded https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.MoveGameObjectToScene.html
Can you post your code ?
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
i have a tilemap with a variable amount of filled tiles, (variables for columns and rows)
how can i then adjust the camera to fit the entire tilemap perfectly?
I am not sure what is your issue ?
This is somehow tricky and I do not know exactly how, but if there is a way, you will need to use Generic Type.
However, I feel that there is a better way to handle things.
First, is there a particular reason why you want a static nested class inside your child ?
Not how things are handled at the moment.
Also, State is not even a field of FooPlus
You would need to do FooPlus.States
ok its just the number of rows/2
hello, I am getting this error and it is not showing me a line from my code:
"ArgumentNullException: Value cannot be null.
Parameter name: _unity_self"
(there are other things that are shown but i didn't understand them)
Maybe a Unity bug, show the rest of the error(s) though
: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <4911eca47f294e18a7b3306f02701303>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
that's all of it
Do you know what is reflection ?
Are you familiar with attribut ?
Do you know what is polymorphism ?
How well do you understand generic type ?
I'm just trying to see what would be something that you could do.
'Cause there is numerous way we can approach this.
what do you guys think of this way of getting a value in a random range
is it better then RandomRange()
Seems like Random.Range with extra steps π€·ββοΈ @spark flower
but what if its a random range betwean 0-1000
isnt it better
Alright, I will make a suggestion on how you could handle your StateMachine and you will say what does not work for you.
in what way would it be better?
How is it better than Random.Range(0, 1000) or (0, 1001)
^
are you just guessing that is the case?
yes
It's wrong because it's going to have a tiny but non zero chance of returning track.Length
Definitely not more performant
how would that be "more performant" bigger number does not mean less performance. int and float take up exactly the same number of bytes
I think you got the answer, just use Random.Range
Also praetor has a point, Random.value can return 1f in which case it would be out of bounds
well im open for knowledge
How can i set the color of the Tiles in my tilemap?
private void GenerateGrid() {
map0.ClearAllTiles();
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
int x = (int)(i - cols / 2f);
int y = (int)(j - rows / 2f);
Vector3Int pos = new Vector3Int(x, y);
map0.SetTile(pos, tilePrefab);
map0.SetColor(pos, Color.red);
}
}
}
```i tried this but it doesnt do anything
the SetTile works but not the SetColor
might need to make sure to set the tile flags to none, or at least make sure the LockColor flag isn't set
quick question, if I have a bool condition that starts false, and a bool conditionChangedSinceLastFrame, would the following code correctly assign it?
conditionChangedSinceLastFrame = condition == (condition = AssignmentFunction());
does it evaluate and store condition before the reassignment?
Given the following, is it only the intialize function that you do not like ?
public class StateMachine {
private State currentState = null;
public void Initialize(State state){
currentState = state;
}
public void Update(){
if(currentState != null)
currentState = currentState.Update();
}
}
public abstract class State {
public abstract State Update();
}
public class AState : State {
public State override Update() {
if(...)
return new BState();
return this;
}
}
public class User {
private StateMachine stateMachine = new StateMachine();
private void Awake(){
stateMachine.Initialize(new AState());
}
private void Update() {
stateMachine.Update();
}
}
why not just split this into two lines so it's more readable?
I could definitely do that, I'm mostly just curious about how this would be evaluated
map0.SetTile(pos, tilePrefab);
map0.SetTileFlags(position, TileFlags.None);
map0.SetColor(pos, Color.red);```
private void GenerateGrid() {
map0.ClearAllTiles();
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
int x = (int)(i - cols / 2f);
int y = (int)(j - rows / 2f);
Vector3Int pos = new Vector3Int(x, y);
map0.SetTile(pos, tilePrefab);
map0.SetTileFlags(pos, TileFlags.None);
map0.SetColor(pos, Color.red);
}
}
}
``` now everything is black haha
what is tilePrefab
show its inspector
thats weird...
are those the tiles placed and is ok if you remove the color part?
when i remove the color part everything is fine
The state itself will know what next state it needs. Look how the update is done. You are not able to know what are all state. You only need the entry state. There is other way to do it.
I mean when you run the script. are they white?
no they have that color
otherwise that blue might be mixing with red, causing it to look black
although is prob really dark purple
red and blue mixes to black
red and blue make purple
try change the color of your tilemap renderer to white and see if the tile is red
ill try
oh yeah it is
so the setColor is adding color?
hm just to the base color
well everything works now thx
Not sure I understand. The way I made it is that every update, the state say what is the next state. (By instanciating the next) It can be itself also.
now it was the tilemap adding the extra tint, the color code was doing what it was supposed to
yeah they blend and not replaced in this case cause of tilemap tint
tints just tint as name suggest they don't replace the color
Hello everyone, tell me where in two scenes 175 mb?
i have a loop that iterates 1000 times every 10 fixedupdate frames in my game, however this creates heavy spikes in fps. Is there a way i can solve that through multi threading etc. (never used it so i don't know if it would work in this case) what would be the best solution?
Do you have asset in a resource folder ?
no
what the hell are you looping through
if you need unity api (except debug.log) then "no" ways for you to multithreads
Do you have reference to an asset in your scene ?
or you can have a look to job system
yes
Then the asset is included in the build with all its dependencies.
Also, Font is treacherous.
can I somehow reduce the weight of the build to at least 50 mb?
Yes. You first need to use AssetBundle to control what is added to your build.
To find out what is included that you are not expected.
explain what you are doing
Does anyone know the dangers of autosave? Like isn't there a higher chance that the player is going to Alt+f4 the game right when it autosave and corrupt the savefile?
your save system should account for this
consider having three autosave files
when you save, you overwrite the oldest one
you then load the newest valid save file
for correctness, I think you'd also want to delete any invalid save files
Yep, you do a save then a move
How do I check if a savefile is corrupt?
so that you don't wind up with three corrupted save files if the user repeately alt-f4's the game lol
a* pathfinding
this is also a good idea: you produce the entire save file, then clobber the old save
1000 iterations seems not much....
Alright so I make 3 savefiles, when tha game save it always overwrite the oldest one. When the the game load it loads the most recently written
Guys, how could I program a hook that when you press a button generates it and makes a parabolic movement that raises my character in 2d (something like spiderman)
not verynoticeable rn
you can use multithreading
but probably will be when i have many enemies
the Jobs system may be relevant for you
it lets you do work on other threads (possibly over many frames)
then you need to limit the search space, consider hierarchical search, i am working on it
break down the problem into smaller ones
lemme check that thanks
you propably need to implement a minheap for this
oh yeah, those are relevant for pathfinding algorithms, aren't they
PriorityQueue comes in a newer .NET version than unity provides
https://stackoverflow.com/questions/48843677/why-dont-we-use-ternary-or-quaternary-heaps
i think it is time to change my minheap to ternary heap....i can write "c code" in c# now with unsafe list
I've been learning about script composition and the single responsibility principle and i've been refactoring my code to implement these. For instance in my top down zombie shooter prototype I've implemented the zombie's attack as such:
{
[SerializeField] private int damage = 10;
[SerializeField] private float knockbackDuration = 1.5f;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
Health playerHealth = collision.gameObject.GetComponent<Health>();
ReceiveKnockback playerKnockback = collision.gameObject.GetComponent<ReceiveKnockback>();
playerHealth.TakeDamage(damage);
playerKnockback.InflictKnockback(gameObject.transform.position);
}
}
}
is this a sensible approach or am i missing the point here?
The player has a movement component, a health component, and a receiveKnockback component
it still feels clunky but im not sure
would an event be more sensible here?
If you follow the principe of OOP, you are violating Tell Don't Ask.
You are asking the Health/Knockback of the player to operate on them. Sometimes, it is a good idea to do that, but in a case of an attack you might want the player to have its word in the takeattack action.
ah, I see
Maybe he has armor ? Or he has a buff that reduce knockback ?
I wouldn't have thought that myself, since you're not directly modifying the health value or directly applying knockback
but you're still missing the chance for the player to decide if it takes damage or knockback, yeah
thanks for the response. i was literally thinking about how it would work if i implemented armour and that prompted me to ask the question lol.
i'll look into tell dont ask, thank you
you're already halfway there
you tell the Health object to take damage
rather than just subtracting from a float
i'm struggling to conceptualize this tell dont ask stuff, im new to oop :/
how exactly do you mean? Do you mean my implementation is correct for the health?
the least flexible option would be something like this
player.health.amount -= 10;
you just unconditionally subtract 10
suppose the player gets iframes (invincibility) for 1 seconds after taking damage
now everyone who hurts the player has to know about that, and correctly check for invincibility before subtracting health
your solution looks like this
player.health.TakeDamage(10);
that's better: the health component can decide if it actually wants to receive that damage
but I think what Simferoce is suggesting here is...
player.TakeDamage(10);
directly telling the player to take damage
the player would then tell its health component to take damage if it agrees
Aaah ok, thank you, that makes sense. Only bit I'm confused about now is which script handles that last functionality
So would I have a "player controller" kind of script through which enemies interact with, then this script decides what happens to the health/knockback states of the player?
Like checmicalcrux, the player should be the one to take the damage.
There is multiple issue with what you are doing, one is like I said earlier, you will have an harder time to implement mitigation for that health/knockback. (This could be fix by making those system modifiable enought)
However, there is also the fact that you will need to rewrite the same code for every source of damage. (Today, it is weapon, but maybe tomorrow it is a trap)
You can, this is the easy way. You can also create something that have that manage the receiving hit.
Something like Hittable.
if (collision.gameObject.TryGetComponent<Hittable>(out Hittable hittable))
hittable.TakeHit(...);
I see. so i could have a hittable component on my player. this component would communicate with the armour state of my player. the hittable component calculates the final damage on player health and then calls the player.health.takeDamage(X)?
Hittable would not know what is a player.
Only that it has a health and knockback.
And, maybe a list of statistic/buffs eventually
If you trully have a LOT of things that behave differently from a player then an enemy, the you could make an Interface instead and implement eveything in the player.
The player being an IHittable. While the enemies/breakable could have the component Hittable.
[RequireComponent(typeof(Health))]
public class Hittable : MonoBehaviour
{
Health health;
Armor armor;
private void Awake()
{
health = GetComponent<Health>();
armor = GetComponent<Armor>();
}
public void TakeDamage(int amount)
{
int mitigatedAmount = Mathf.Max(amount - armor, 0);
health.ChangeHealth(-mitigatedAmount);
}
}
Something like this?
Exactly
brilliant, thanks, i understand now
this is turned on on my camera, but do I need to turn on something else/script in actual dynamic culling? Or does this work dynamically
Hello, is there an alternative to Screen.currentResolution.refreshRate?
why?
...but I cannot do that because it is a procedural world
so I would have to script in something similar
does disabling the mesh renderer on an object "cull" it
would the camera not try to draw it
Screen.currentResolution doesn't work in some cases, and I need information about the current refresh rate.
what is this? What does it do? and can I optimize it
pretty sure that's the time spent waiting for the gpu to spit out the image
it goes really high when my macbook is straining to render 4K volumetric fog lol
huh
its
being bad
I turned off all of the mesh renderes and this became the most performance heavy thing
the game runs 60fps in the small unity window, but when I fullscreen it, it falls to like 18
any idea why that might be happening
is this HDRP?
no
then what is it?
generic pipeline
it is
and I cant switch to HDRP because it breaks all my materials and doesn't look as nice when I manually fix them
but this works for me
ill see if I can tweak a setting somewhere
I mentioned HDRP because it can get pretty slow even in a basic scene
if you have stuff like volumetric fog going
create a new empty scene and check how it runs
alright
it runs blisteringly fast
but it does drop signifigantly when I fullscreen it
and yes that thing the GFX.Waitforpresent it what is causing the lag
it drops from like 400 to 150
let me check the docs
Indicates that the main thread was ready to start rendering the next frame, but the render thread did not finish waiting for the GPU to present the frame. This might indicate that your application is GPU-bound. To see what the render thread is simultaneously spending time on, check the CPU Profiler moduleβs Timeline view.
If the render thread spends time in Camera.Render, your application is CPU-bound and might be spending too much time sending draw calls or textures to the GPU.
If the render thread spends time in Gfx.PresentFrame, your application is GPU-bound, or it might be waiting for VSync on the GPU. A WaitForTargetFPS sub-sample of Gfx.WaitForPresentOnGfxThread represents the portion of the Present phase that your application spent waiting for VSync. The Present phase is the portion of time between Unity instructing the graphics API to swap the buffers, to the time that this operation completed.
Imma read this and divine what I can
any idea what this means or how I can fix it
I dont understand it too much
the render thread sets up the frame, then tells the gpu to display it
if the thread is spending most of its time just sitting there in Gfx.PresentFrame, then you're gpu-bound, because the thread finishes its work quickly
change the rendering settings to make the scene cheaper to render or buy a better gpu, pretty much
"gpu bound" just means the gpu is the bottleneck
the cpu can get the scene ready faster than the gpu can render it
ah
wdym change the rendering settings to make the scene cheaper
where do I do that
see the Quality section of your project settings
you might try just switching the quality level
to a lower one?
these are the HDRP ones
ahhh
the built in RP has a different list
let me check
double click one to make it the default, iirc
I know that switching from High Fidelity to Performant doubled my FPS on my macbook
Anyone know a way to screen wrap without teleporting? I want my boids to wrap around but still have an affect on each other. Like boids on the very left edge can affect boids on the very right edge of the screen.
So far I've been having a relatively easy time working with this and adjusting certain things about the code to my liking. I've got it moving along the spline, got it facing forward, managed to simulate gravity to some extent too. Only thing I'm worried about right now is stopping movement in any give direction when colliding with an environment object considering that, at the moment, I'm moving along the spline via length placement. I've got some ideas in mind to overcome this, but hopefully they work out, even if they're a bit crude. Once again thank you for your help!
you'd have to implement your own distance function (amongst other things, probably)
going back to the discussion about composition, is something like this okay?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class ZombieAttack : MonoBehaviour
{
[SerializeField] private int damage = 10;
[SerializeField] private float knockbackPower = 30;
private void OnTriggerEnter2D(Collider2D collision)
{
GameObject collidedObject = collision.gameObject;
TryHitObject(collidedObject);
TryKnockbackObject(collidedObject);
}
void TryHitObject(GameObject objectToHit)
{
if (objectToHit.TryGetComponent(out Hittable hittableObject))
{
hittableObject.TakeDamage(damage);
}
}
void TryKnockbackObject(GameObject objectToHit)
{
if (objectToHit.TryGetComponent(out Knockbackable knockbackableObject))
{
knockbackableObject.InflictKnockback(gameObject.transform.position, knockbackPower);
}
}
}
Looks great
Will this work?
handAnimator.runtimeAnimatorController["R"] = RA;
I need to replace R animation in hand animator by RA animation clip
Use AnimatorOverrideController
This is the exact use case for it
π
Usually you want to merge the concept of hitting and knockback. However, it can varies on what your game actually is and how everything plays out.
Think about the following: If you ever need to implement an other source of an attack, let's say a trap, would you need to reimplement the same behaviour ? Would you need to do TryHitObject and TryKnockbackObject ? If so, you might be in a situation where both concept are tighly couple to the concept of getting hit. In this case, you might want to define an attack/hit as having a knockback force in itself.
public struct Hit {
public float Damage;
public float KnockbackForce;
public Vector3 KnockbackSource;
}
...
hittableObject.TakeHit(new Hit() { Damage = damage, KnockbackForce = knockBackforce, KnockbackSource = gameObject.transform.position});
...
public void TakeHit(Hit hit) {
if(CanBeKnockback && hit.KnockbackForce > 0) {
// Kockback !
} else {
// Notify (or not) that the object cannot be move.
}
if(CanBeDamaged && hit.Damage > 0) {
// Damage !
} else {
// Notify (or not) that the object cannot be damaged.
}
}
(This merely an example, there is multiple things that are wrong)
To help you make the correct choice, you might want to look what your game will look like. Are you gonna expand on this with an other module ? By example, you might want to have a durability system. Are you gonna do TryGetDurabilityObject ?
The fundamental of good decision is how to minimize the amount of changement in your code. In your situation, with the current suggestion of having TryHitObject and TryKnockbackObject inside the zombie attack seem to not be a good idea as you might need to change things twice (In the attack and in a potial script like a trap) instead of once if you ever do multiple source of damage, which is something I am expecting to see at some point.
Im gonna see if this solves the issue
It works but why it looks like a star instead of a cone?
thank you so much. i did have these thoughts. its just so hard to know what to try when you haven't seen anything before. i think combining them is the right call
This is your code isnt it ? You are doing it on 360Β°.
I got a little help from chatgpt but seems it messed up a bit
This is why, you need to understand what you are doing.
I was wondering why the heck did you comment every line in spanish also.
Knowing coding and knowing what you are doing are seperate things.
Most people comment in english same if their native language is not.
whatever still how I can fix the rays
I know, I'm not a native english speaker either.
Are you serious ?
This is truly elementary.
You would know if you understood what you are doing.
I dont know math -.-
Yeha there is
Are you saying that a single division is math ?
Just tell me how to fix it and stop complaining
i have this code for left/right camera rotation around the character and making the camera follow the character, but i have issue that when i rotate the camera, the view starts flickering right to left, and the more i rotate it the more it flickers
what could be causing this flicker?
{
[SerializeField] private int damage = 10;
[SerializeField] private int knockbackPower = 30;
private void OnTriggerEnter2D(Collider2D collision)
{
GameObject collidedObject = collision.gameObject;
TryHitObject(collidedObject);
}
void TryHitObject(GameObject objectToHit)
{
if (objectToHit.TryGetComponent(out Hittable hittableObject))
{
hittableObject.TakeHit(damage, knockbackPower, gameObject.transform.position);
}
}
}
...
public class Hittable : MonoBehaviour
{
private Health health;
private void Awake()
{
health = GetComponent<Health>();
}
public void TakeHit(int damage, int knockbackPower, Vector3 knockbackSource)
{
TakeDamage(damage);
if (TryGetComponent(out Knockbackable knockbackableObject))
{
knockbackableObject.InflictKnockback(knockbackSource, knockbackPower);
}
}
public void TakeDamage(int amount)
{
health.ChangeHealth(-1 * amount);
}
}
...
``` Do you think this is a good approach?
i was concerned because not all hittable objects should be knockbacked, such as static objects, but i think it works with my code
It is a start. Now, make the game and stop linger on details. π
true xD i just came back to this game after 3 months and realised how much of a mess everything was
but i suppose the best way to learn is to continue until i run into the wall and discover why i have to do things in a good way
not being able to remember what i wrote yesterday caused me to become a better programmer.
how could i make sure a variable implements an interface and inherits from a class at the same time? (if any, ) what would be the syntax for something like that?
just put the class first
if(varname is IInterface ivar)
oh wait
i thought you were talking about a class declaration
yeah, just check both in sequence
correct term is object implements
float a = 5;
if(a is IComparable icomp && icomp is float f)
{
}
how do I make it so that when I move my cinemachine camera, the player's turn is delayed?
I meant on declaration. I want to declare a monobehaviour class that implements an interface but can't have another class implement/inherit them both
Like I'm another script.
MonoBehaviour IInterface ClassName;
you can implement as many interfaces as you like
this isnt valid syntax
What would be valid syntax?
It is one of the other. Then you cast the other in what you want.
the one Simferoce posted
So (MonoBehaviour) IInterface ClassName?
No. You need to choose one or the other.
Hm. Idk what to do then. For some reason, even while using the new keyword, if I make a new class implementing IInterface and inheriting from MonoBehaviour (so I can access it in unity), any function I call on it with the new keyword ends up calling the one from the class the previous class if that made any sensw
You could alternatively combine both in an other class.
public class MyInterfaceMonoBehaviour : MonoBehaviour {...};
public class MyObject : MyInterfaceMonoBehaviour {...};
I can't because it requires me to implement the interfaces function and it doesn't get overridden by the new function even using new
You definitly need to read: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/polymorphism
Does new not override a previously declared function inside a parent class?
No.
What you are doing is: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-modifier
If class A : B, B impl void some_func(), and A impl new void some_func(), won't A.some_func() run A's function instead of B's
Read on polymorphism
I'm not sending those links for fun.
hiding is like hiding behind a tree
there is a tree behind this one
but you dont see it
but if you walk around this tree you will see the one behindit
the both trees are still there
Isn't
public class BaseC
{
public static int x = 55;
public static int y = 22;
}
public class DerivedC : BaseC
{
// Hide field 'x'.
new public static int x = 100;
static void Main()
{
// Display the new value of x:
Console.WriteLine(x);
// Display the hidden value of x:
Console.WriteLine(BaseC.x);
// Display the unhidden member y:
Console.WriteLine(y);
}
}
/*
Output:
100
55
22
*/
Exactly what I'm doing (taken from examples)
What do you mean ? It cleary is ?
Also, you are using static.
So, shouldn't it call the second function and not the one from the base class
I'm not anymore: this is a different thing
statics are unique per type, static type of a type is a separate thing
does anyone know why my player is facing to the side and not forward?
The only way you can modify behaviour of a static with a sort of inheritance is through generic.
public class MyBase<T>
{
public static string GetValue => typeof(T).Name;
}
public class MyClass : MyBase<float>
{
}
public static void Main(string[] args)
{
Console.WriteLine (MyClass.GetValue);
}
i have no idea why its doing that
rename to mp4 and repost
its still equivalent to just declaring it twice
just in this case only one type will be generated
nah, 2
since you provided generic arg
You can do all sort of funcky things with that. Not really something you should do to be honest.
Not sure what you mean, but it does change the behaviour depending on what the argument is pass through while also retaining the possibility to call the GetValue without needing to declare both, resulting in a sort of static polymorphism.
i mean that compiler will generate 2 distinct classes, MyClass and MyClass<float> both containing unique GetValue
Yes, it will.
It just removes the need to actually do it yourself.
I mean, it will only generate MyClass<float> ?
no, MyClass is a unique class
i confused myself you are correct
but only for the non static
both will generate separate unique statics
You gonna only have 1 version of GetValue at the end because we only provide 1 version of MyBase<T> which is MyBase<float> ?
no
public class BaseClass {
public void some_func() { something(); }
}
public class DerivedClass : BaseClass {
new public void some_func() { other_thing(); }
}
class User {
BaseClass MyClass = new DerivedClass();
void Main() {
MyClass.some_func(); // BaseClass.some_func(), want DerivedClass.some_func().
}
}
i want some_func() to run other_thing(), not something(). how could i do that?
both MyClass and MyClass<float> will have their own unique GetValue
By reading on polymorphism
a non static class cant inherit static properties since static classes cant be inherited
You cannot have GetValue directly on MyClass ? It needs to have a type to actually be compiled.
GetValue is static, you cant invoke/access static member of the base class through instance, only through type name
If you do MyClass2 : MyBase<float>. You gonna have 2 GetValue.
Both there is no GetValue inside MyBase<T>
It is only a template
If you do not provide the (T), it wont.
but you did provide it
The only provided (T) is from MyClass
I have, and unless im casting DerivedClass into BaseClass (which i sincerely hope isnt the case), i should be running otherthing, which im currently not.
which is a separate type
Alright, you are right, I did specify MyBase<float>.
MyBase<float>.GetValue()
MyClass.GetValue();
Is not the same. Forgot that I somehow specify MyBase<float> inside the declaration of MyClass.
Friend, read again.
Everything you want is there.
You can use Youtube also, if you prefer.
i understand you are learning c#, but i believe you are trying to use the wrong tool for the job
most likely you want to use a virtual method
im familiar with polymorphism; im just new to c#
Then, learn polymorphism in c#.
It is going to be fast.
If you already know the concept.
public partial struct TTT : ITTT
{
public enum TypeId: byte
{
XXX,
ZZZ,
KKK,
}
[FieldOffset(0)] public TypeId CurrentTypeId;
[FieldOffset(1)] public XXX m_XXX;
[FieldOffset(1)] public ZZZ m_ZZZ;
[FieldOffset(1)] public KKK m_KKK;`
}
can unity serialize it?
can you give an actual example where it's needed / what you're trying to accomplish there?
@lavish ridge ```cs
class Foo
{
public string name => "foo";
}
class Foo1 : Foo
{
public string name => "foo1";
}
class Foo2 : Foo1
{
public string name => "foo2";
}
static void Main(string[] args)
{
Foo2 foo2 = new Foo2();
Console.WriteLine(foo2.name);
Console.WriteLine(((Foo1)foo2).name);
Console.WriteLine(((Foo)foo2).name);
Console.ReadKey();
}
foo2
foo1
foo
virtual methods did the trick; thanks for the help yall
doubt it, but you can use ISerializationCallback
That would be suprising, even the less you could try. However, you should ask yourself if there is an other way to structure things.
There is also the possbility to simply do the serialization manually with https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
Here links that could help you:
https://docs.unity3d.com/Manual/script-Serialization.html
https://blog.unity.com/engine-platform/understanding-unitys-serialization-language-yaml
whats
SerializationCallbackReceiver don`t work with structs =/
{
// Using BeginProperty / EndProperty on the parent property means that
// prefab override logic works on the entire property.
EditorGUI.BeginProperty(position, label, property);
// Draw label
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
var typeRect = new Rect(position.x, position.y, position.width, 20);
EditorGUI.PropertyField(typeRect, property.FindPropertyRelative("CurrentTypeId"), GUIContent.none);
string typeName = property.FindPropertyRelative("CurrentTypeId").enumNames[property.FindPropertyRelative("CurrentTypeId").enumValueIndex];
var otherRect = new Rect(position.x, position.y + 20, position.width, 20);
var prop = property.FindPropertyRelative($"m_{typeName}");
SerializedProperty it = prop.Copy();
SerializedProperty end = prop.Copy();
end.NextVisible(false);
while (it.NextVisible(true) && !SerializedProperty.EqualContents(it, end))
{
EditorGUI.PropertyField(otherRect, it);
otherRect.y += 20;
}
EditorGUI.EndProperty();
}```
i have created a custom property drawer but it only saves the value for the last item
Here it is m_KKK
True The callback interface only works with classes. It does not work with structs.
Can i somehow copy the struct from property to a new object, edit it and apply back to main object?
ok
You will need to have a container to hold the value.
The object in itself wont be able to hold the value if it is not serialized.
@ashen yoke
How do i do it?
It is serialized but all 3 types are on same position and the last one always overrides the value
What is the result in the .prefab or scene ?
see how the place is face to the side when walking forward? Idk how to fix that.
Did you try rotating the body by 90 degrees?
TTT:
CurrentTypeId: 0
m_XXX:
UUU: 123
WWW: 123
m_ZZZ:
UUU: 123
m_KKK:
UUU: 123
UUA: 123
UUB: 123
UUC: 123
Curious, I guess it does not know how to handle things.
The obvious choice would be to rething your architecture.
I`m creating a polymorphic struct system for ECS
Otherwise, you gonna need to have an other object that wraps this one.
Polymorphism and ECS does not go well together.
It is not the same paradigm
i really need it
ECS is Data-Oriented and GameObject is OOP
My game is super complex and it is the best way to handle some things
You should use Data-Oriented pattern.
Or have an Hybride approach.
DataOriented is fundamentally not compatible with polymorphism.
Due to the layout of the data.
thats a union
It is polymorphic if you use source generators
public interface ITTT
{
int Key();
}
[Serializable]
public partial struct XXX : ITTT
{
public int UUU;
public int WWW;
public int Key()
{
return WWW;
}
}
[Serializable]
public partial struct ZZZ : ITTT
{
public int UUU;
public int Key()
{
return UUU;
}
}
[Serializable]
public partial struct KKK : ITTT
{
public int UUU;
public int UUA;
public int UUB;
public int UUC;
public int Key()
{
return UUU;
}
}```
original
public partial struct TTT : ITTT
{
public enum TypeId: byte
{
XXX,
ZZZ,
KKK,
}
[FieldOffset(0)] public TypeId CurrentTypeId;
[FieldOffset(1)] public XXX m_XXX;
[FieldOffset(1)] public ZZZ m_ZZZ;
[FieldOffset(1)] public KKK m_KKK;
public int Key()
{
switch(CurrentTypeId)
{
case TypeId.XXX:
{
var r = m_XXX.Key();
return r;
}
case TypeId.ZZZ:
{
var r = m_ZZZ.Key();
return r;
}
case TypeId.KKK:
{
var r = m_KKK.Key();
return r;
}
default:
{
return default;
}
}
}
}```
generated
TTT is a tagged union that represents all structs that implements ITTT
hello, im tryna make it so when you press space an image becomes 100 percent alpha, and when you press it again it goes back to 0
im having issues with the c in the if statement not being registered or whatever
c does not exist in that context because it is declared inside of Start so it's scope is only within Start
c is a local variable in Start. it does not exist outside of that method . . .
so i just say "Cam1.color = c;" at the beginning of update?
and it will work
or do I also include "Color c = Cam1.color;"
should I just remake the character?
well this obviously won't work considering i just told you c does not exist in Update
oh yeah true
the only time you declare a new variable inside of start would be if it already existed outside a function
= is assignment == is to compare
i dont think its that
It's definitely that
255
so do I do Color c == Cam1.color;?
yes
No
im dumb okay
That's an assignment
i am the ape brain level of coding
Assignment is =
okay that makes sense
where it says imput getbutton down
in a if statement your comparing
your not setting
this is what im with rn
so its if( something == something)
in the if staments change it to ==
yes
Why is it red
cuz its wrong
Oh yeah =
whys the c red
Didn't see it the first time
i still have some red cs
if you're stuck i'd look up a tutorial on if statements and comparisons. it's a #π»βcode-beginner topic . . .
What does it say
Why are you trying to redeclare your c variable
Oh yeah
ok i fixed it
does it work now
declaring it multiple times was the issue
My point is that you should use DataOriented pattern in a DataOriented context. Fundamentally, polymorphism is not something that it is expected in a DataOriented approach. Usually behaviour are in System not in Data which make the whole point of polymorphism kinda useless.
when I press Jump, an image should pop up, when I press it again, it should dissapear
its not working
Also yes still have 100 instead of 1
dude
just setactive(false)
it doesnt just not work
it just doesnt act like its a thing
For your issue, unfortunaly, I do not see anyway to make it works with Unity Serializer.
well yeah im sure theres an issue
but I cant figure it out
yeah ik
transform.gameobject.SetActive(true);
what is the script on
is the script on the object your trying to become visible./invisible
okay wait so do i do the input stuff, and then && transform.Cam1.SetActive(true/false)?
specificly, i want to make it so when you press space, a camera opens up which will be an image, and then when you press it again the image will disappear
im making a bad fnaf bootleg cuz im bored
ok 1 sec
i will generate authoring class
is my question for beginner or general?
what?
blud isnt talking to u
almost done with the script
anyone know why this is happening
okay
just testing it now
heres the vid
alr it works π
yay
here you go
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class NewBehaviourScript : MonoBehaviour
{
public bool IsActive()
{
if (gameObject.activeInHierarchy == true)
{
return true;
}
else if (gameObject.activeInHierarchy == false)
{
return false;
}
else return false;
}
private void Update()
{
if (Input.GetButtonDown("Jump") && IsActive())
{
gameObject.SetActive(false);
}
else if (Input.GetButtonDown("Jump") && IsActive())
{
gameObject.SetActive(true);
}
}
}```
just rotate the model to look where you want it to face
I would establish game object as cam1 first right
but thats extremely basic. I would really recommend getting more backround knowlage of C# and unity if you dont know how to do that
no just put it on the object
whatever object is attatched to it will dissapear when you jump
that doesnt work
the scripts arre disabled
hance you cant re enable it
u need to download input system
window -> package manager -> input system
@wide barn even when I rotate it, it still looks to the side
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PutOnAEmptyObject : MonoBehaviour
{
public GameObject objToManipulate;
public bool IsActive()
{
if (objToManipulate.activeInHierarchy == true)
{
return true;
}
else if (objToManipulate.activeInHierarchy == false)
{
return false;
}
else return false;
}
private void Update()
{
if (Input.GetButtonDown("Jump") && IsActive())
{
objToManipulate.SetActive(false);
}
else if (Input.GetButtonDown("Jump") && IsActive())
{
objToManipulate.SetActive(true);
}
}
}```
fixed
u need to attack this to a empty gameobject
and drag the gameobject u want to make invisible in the inspector
i didnt test it so lmk if it doesnt work
delete the using statment that doesnt work
and still see if it still works
click x there
good
inputsystem is still red tho
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PutOnAEmptyObject : MonoBehaviour
{
public GameObject objToManipulate;
private void Update()
{
if (Input.GetButtonDown("Jump") && objToManipulate.activeInHierarchy == true)
{
objToManipulate.SetActive(false);
}
else if (Input.GetButtonDown("Jump") && objToManipulate.activeInHierarchy == false)
{
objToManipulate.SetActive(true);
}
}
}```
this is better to use
yes thats good
anyone has a save system using json files i can take a look at the code? for god's sake I cant understand it no matter how much tutorials i watch
look up dan pos inventory system save/load
how do I make an input system
dan pos? are they youtuber ?
yes
input system is red
let me know when you guys are done
rightclick create inputactions
not see if it works cuz i honesly idek anymo
β Daily reminder to backup your projects β
inputsystem is still red
look up how to install it then
How do I get rid of this error when I stop the game. It works during runtime but when I stop game it comes up with an error
nvm I got it
i just deleted the input system and it worked
like removed it from the code
thanks for the help
thats wierd
why what is still hapenning
the player faces to the the side when moving forward
its always facing 90 degrees in the wrong direction
seeing your code would be helpful
then where you handle rotation just -90
The 3D model is probably oriented incorrectly
or that
how do i orient it right?
wdym?
how would I do that
Right click > Create Empty Parent
Or make an empty object then set the object as it's child then rotate it
i fixed it
just re-oriented it in blender
nvm
@leaden ice how do I do the parent thing
because doing it in blender isnt working
nvm i got it
I am very confused, this code does actually change the window resolution in a build, but the log output is fixed to 1920, 1080 specifically (both in a build and in-editor), even though the window size itself is certainly much smaller than that, what could cause this?
Screen.SetResolution(500, 500, false);
Debug.Log(Screen.currentResolution.width + "," + Screen.currentResolution.height);
the screen size =/= the window size
How would I set the window size? Is there a different API for that? I thought the Screen.SetResolution would apply if not in fullscreen mode, cause it does actually change the window size to 500x500, it just doesnt reflect that in the log
oops hang on. here i found this in the documentation "A resolution switch does not happen immediately; it happens when the current frame is finished."
so its applying correctly but its just doing it at the end of the frame (after your log statement)
so before i try and make my own, is there a script out there already that looks for a path on the script? such as an input field and then uses the input text as a way to load from file then applies the texture to a premade material? idk what id have to look up to even find that
Hmm, thats odd, I also tried delaying the log with a coroutine after 3 seconds, and it still seems to be the same
its works in windowed
namespace SaveLoadSystem
{
public static class SaveDataManager
{
public static SaveData currentSaveData = new SaveData();
public const string fileName = "/savefile.json";
public static bool Save()
{
var path = Application.dataPath + fileName;
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string json = JsonUtility.ToJson(currentSaveData, true);
File.WriteAllText(path, json);
Debug.Log(path);
return true;
}
}
}
Why i cant use Save() Method in other scripts?
I mean like this in another script file
SaveDataManager.Save();
missed the rest sorry
you probably forgot to add using
since you put it in a namespace
are you referencing this script correctly in the other script?
using what?
SaveLoadSystem
oh tha name space?
it says namespace
yeah namespace
I added using SaveLoadSystem in the 2nd script that I want to use the Save() method, still not working
show code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SaveLoadSystem;
public class ButtonManager : MonoBehaviour
{
public void ClickSave1()
{
SavaDataManager.Save();
}
}
seems like you have some other issue somewhere
this should work as is
does the project compile?
lol
Sava
you dont have you IDE setup?
use guides here
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
It draw a red line under SaveDataManager says does not exist in the current context
It could be in an unreferenced assembly, if you are using assembly definitions.
yes because you have a typo
no my ide is fine, I use it for a long time on other projects
Im using this code for testing, 3s later the build does go into Windowed mode, 3s after that the "..." text updates to 1920, and im not sure why o.o
IEnumerator Test()
{
ts.text = "...";
Screen.fullScreenMode = FullScreenMode.Windowed;
yield return new WaitForSecondsRealtime(3f);
yield return new WaitForEndOfFrame();
Screen.SetResolution(500, 500, false);
yield return new WaitForSecondsRealtime(3f);
yield return new WaitForEndOfFrame();
Debug.Log(Screen.fullScreenMode + "," + Screen.currentResolution.width + "x" + Screen.currentResolution.height);
ts.text = Screen.fullScreenMode + "," + Screen.currentResolution.width + "x" + Screen.currentResolution.height;
}
void Update()
{
if (UnityEngine.InputSystem.Keyboard.current.gKey.wasPressedThisFrame)
{
StartCoroutine(Test());
}
}
oh now its working!!!
there wasn't any typo but It showed as a typo til I use autocomplete, Weird
thanks a lot guys
no no I did save both scripts
no, they are saying you spelled it Sava when it should be Save
as shown in the screenshot
intellect has nothing to do with it
programmers develope the habbit of really paying attention over long time
myabe its beacuse its like 3am here lol
that's the stupid part, go to sleep π
will do
webGL builds. of your code
is it possible to read text files in a WebGL build
Hey, trying to attach a textobject to a cube that will move and rotate with said cube. I have it working except for the text being mirrored, and I can't really figure out how to fix that. Here is the relevent code. When attempting further rotations the text will become offcenter, and the offset vector will no longer work.
public string suit;
public string value;
public Font font;
public float characterSize = 0.1f;
public Vector3 offset = new Vector3(-0.5f, 0f, -0.25f);
// Start is called before the first frame update
void Start()
{
// Create a new game object and attach a TextMesh component to it
GameObject textObject = new GameObject("Text");
TextMesh textMesh = textObject.AddComponent<TextMesh>();
// Set the text to render
if (suit == null || value == "0") {
textMesh.text = "";
}
else {textMesh.text = value + suit;
}
// Set the font
textMesh.font = font;
// Set the font size to match the game object size
Renderer objectRenderer = GetComponent<Renderer>();
Bounds bounds = objectRenderer.bounds;
// float fontSize = Mathf.Min(bounds.size.x, bounds.size.y, bounds.size.z) / characterSize;
textMesh.characterSize = 0.03f;
textMesh.fontSize = 255;
// Set the font color to black
textMesh.color = Color.black;
// Set the position and rotation of the text object
textObject.transform.position = transform.position + Vector3.up * bounds.extents.y + offset;
textObject.transform.rotation = Quaternion.LookRotation(Vector3.up);
// Set the text rendering mode to Smooth
textMesh.font.material.mainTexture.filterMode = FilterMode.Trilinear;
// Make the text object a child of the current game object
textObject.transform.parent = transform;
}```
^
if anyone can solve my problem
thank
you
is there a way to make landing less harsh when I land after jumping
Less harsh in what way?
so when I land after a jump, the player seems to clip into the floor for a split second
This depends on how youre jumping is set up, for example, perhaps your βisGroundedβ check isnβt accurate
how do i know if it inst accurateA?
Just debug when the boolean is printing true and false, if you are using a CharacterController component, try changing the skin width and step offset
Again, there are quite a few ways your jumping could be implemented, but to me it sounds like however it is setup, youβre ground check isnβt accurate enough
I seem to be generating a fair chunk of garbage (1.1kb) per frame in this function, according to the profiler. Any ideas? I already tried disabling the Debug.DrawRay() calls, but that didn't seem to solve the issue:
public bool IsSectionVisible(Vector3 position)
{
Vector3 origin = GameManager.Instance.myPlayerLink.playerEntity.fpsCam.transform.position;
Vector3 direction = new Vector3(
position.x,
position.y + (origin.y - GameManager.Instance.myPlayerLink.playerEntity.transform.position.y),
position.z) - origin;
Physics.RaycastNonAlloc(origin, direction, raycastHitsNonAlloc, direction.magnitude + 1, SolidLayerMask);
foreach (RaycastHit hit in raycastHitsNonAlloc)
{
Bounds bounds = hit.collider.GetComponent<Bounds>();
if (bounds != null)
{
if (!visibleSections.Contains(bounds.section))
{
Debug.DrawRay(origin, direction + direction.normalized, Color.green);
return true;
}
continue;
}
else
{
Debug.DrawRay(origin, direction + direction.normalized, Color.red);
return false;
}
}
return false;
}```
Does anyone have a good tutorial on physics in c#?
I wanna learn to control physics thru scripting and all i seem to find is stupid videos only using 2d rigibodies
thanks man, I've been watching tutorials and reading other's code about save / load system for like 3 days, non of them teach it like this tutorial. Exactly what I wanted for my game.
Whoops, figured out what was going on, I was using the wrong part of the API... o.o
Not sure how much this would be contributing to that 1.1, though using new calls and foreach can generate garbage, you could try making a Vector3 var you can set your direction to instead, and try a normal for loop and see if it has any significant change, if not you can also enable "Deep Profile" and "Call Stacks" on the profiler, which should let you expand into what is causing GC to fire, it could give you ideas werelse you can look
Oh thanks! I forgot about deep profile, I'll try that. Does foreach generate garbage on it's own? Not exactly sure how that works
Hello! I'm trying to change an object's rotation when it collides with another object!
I used a DrawLine to check if the rotation was correct and it was, but for some reason the object isn't rotating properly :/
`private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, transform.position + desiredRotation * 3);
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Node"))
{
Vector3 newRotation = other.GetComponent<NodeGizmo>().ReturnRotation(transform);
desiredRotation = newRotation;
transform.rotation = Quaternion.LookRotation(newRotation, Vector3.up);
}
}`
DeepProfile points to the .GetComponent call as the main culprit. Though, I'm not sure what else to use in place of that
I believe it does, if you had a collection of say 10 items, and you do a foreach(var x in collection), youd be creating 10 "x"s to represent each index (or however many the loop gets through), if you do a for(int i = 0; i < collection; i++), youd be creating 1 "i" that can be used to reference each index, though I could be wrong on how "foreach" stores "x" - for the GetComponent, in this case, you should be able to access the hit.collider.bounds directly, so you may not even need the call
Ohhh I see what you mean. Yeah, if the thing's reference doesn't already exist or something like that it'd make 10 x's and therefore garbage. Gotcha.
And I should've clarified, these bounds are not the default unity bounds, but a custom monobehaviour I made for a level generator, which is why I'm a bit stuck with .GetComponent()
someone plz help ive been trying to get my sprite to jump in a 2d platformer there arent any errors according to visual studio so idk whats happening: https://gdl.space/fuyoxinodu.cpp
Is your ide configured
ye
Probably want to also explain what's wrong then ;p
Ah I see, you could maybe see if using TryGetComponent(out T varName) could help, AFAIK, it shouldnt allocate when looking for the component: https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
don't get tricked by red herrings if you're profiling while in the editor
You are amazing!
Sounds like it worked out
Yep, now to address the other 4kb garbage per frame from other stuff. Yippee π
Hey there, I've got the following setup to wait for the completion of a coroutine, although I'm getting some weird results.
public IEnumerator RequestMenu(string menu, bool closeCurrentMenu = false)
{
if (closeCurrentMenu && ActiveMenu != null)
{
print("1");
yield return StartCoroutine(CloseCurrentMenu()); //Any code after this never runs.
print("2");
}
}
public IEnumerator CloseCurrentMenu()
{
if (ActiveMenu == null)
yield break;
GameObject currentMenu = ActiveMenu;
Animator animator = currentMenu.GetComponent<Animator>();
animator.SetBool("IsOpen", false);
Cursor.lockState = CursorLockMode.Locked;
yield return new WaitUntil(() => animator.GetCurrentAnimatorStateInfo(0).IsName("Pause Menu Idle"));
currentMenu.SetActive(false);
ActiveMenu = null;
print("Complete");
}
When running StartCoroutine("SomeMenu", true) I would expect my console output to look like:
1
Complete
2
Although it actually looks like
1
Complete
It seems the CloseCurrentMenu() Coroutine is finishing, although the yield in RequestMenu() is ignoring it's completion.
you deactivated the GameObject
this kills all coroutines running on it (they will not resume from their yields)
I'm deactivating a seperate GameObject, not the one with this script
might wanna double check which object the coroutine is running on
i.e. how are you starting the RequestMenu coroutine
the script that the code lives on doesn't matter. What matters is which object/ script StartCoroutine was called on
(for this reason I consider it bad practice to call StartCoroutine on another script's coroutine)
Ah this was the issue. That makes sense now that you mention it..
I had the coroutine started on a button under a menu, which is being disabled, although the coroutine itself lives on a separate GameObject.
Thanks for pointing that one out, had me stumpt for a couple hours.
I have a seesaw object how can I detect when its tilted the opposite side?
example figure 1 is the start , i wanna detect when its like figure 2 in the below image
is it possilbe to make have an animation stay/pause at a certain point? I want to have any object rotate 90 degrees when I click the mouse button, but I want it to stay at 90 degrees if I am holding the mouse button. Then when I let go the object returns to 0
You could perhaps start a coroutine when you press and release the mouse button
does anyone know if it's possible to serealize this kind of fields in order to see when they are changed in Inspector?
private int NumberOfVisibleLines
{
get => numberOfVisibleLines;
set
{
if (value != numberOfVisibleLines)
{
Debug.Log("NumberOfVisibleLines was changed!");
numberOfVisibleLines = value;
AlignTypingField();
}
}
}
Hello,
I'm trying to read the vector of my mouse to make a fps
but this is not working :
public void OnLook(InputValue input){
Debug.Log("View");
}```
can someone explain me why please ?
For learning purposes I am working on a tictactoe game. It's in VR (but my question isn't about VR), and I want the AI to use the same tiles (X or O depending on who's which) as the user would. My question is about the GetComponent bit. aiPiece is a prefab of a tile and StartManualInteraction expects an XRGrabInteractable. But my IDE (Rider) is moaning about GetComponent being expensive. Normally I'd put this in Awake but placing a new tile happens when it's the AI's turn.
How am I supposed to do this? Should I ignore my IDE? Should I create a cache of 5 tiles (max number of moves) in Awake? Pasting code because it's short:
private void MakeAIMove()
{
_availableSockets[Random.Range(0, _availableSockets.Count)].StartManualInteraction(Instantiate(aiPiece).GetComponent<XRGrabInteractable>());
}
I realize it's silly in the context of 5 tiles, with max 9 tiles in the entire game. But I'd like to learn the "right" way so that I get it when it actually matters
Personally I'd say the 'right' way is the thing that achieves the desired functionality, within the necessary performance requirements, as quickly and cheaply as possible.
GetComponent is expensive when you're using it heaps. If the GetComponent call only happens once per turn (I'm assuming each turn is maybe a couple of seconds long minimum) then it wouldn't be happening all that often. It also makes sense to use it if you have to identify an instance of a script on a new object, which you didn't know you'd have to check.
E.g. in the FPS I'm making, whenever one of my bullets hits a surface, it runs GetComponent to check for a valid enemy hitbox, before dealing damage to said hitbox. I use it freely there because the bullet has no way of knowing beforehand what it will hit, and all the physics systems I could use for hit detection will return a Collider for the hit object, which won't have any info about the hitbox and damage functionality.
Hm, but you can cast the other actor right? lol wrong game engine, sorry.
Thanks for that. Yes each turn has roughly 5 seconds in between
?
yeah 'actor' sounded like UE lingo
My bad, been switching around a lot past few weeks.
you only ever instantiate one piece at a time right?
Yes, and only when it's AI's turn. Player pieces are pre-instantiated.
Your pieces are hidden and you have to find them before a timer runs out. It's dumb π
so :-
Add a static variable to XRGrabInteractable
public static XRGrabInteractable lastInstance;
fill it with
lastInstance = this
in Awake
then use that variable after you instantiate aiPiece
That's nasty, I love it π
Although I don't think awake gets called before I call GetComponent, or is that a syncronous process?
Oh shit I think I figured out my problem! I realised that (a) I was looking in the wrong folder, and (b) I was looking in the wrong project (the app we're working on consists of 2 different projects that both use addressables, for complicated reasons)
Do i have to install Microsoft.CodeAnalysis by myself?
Yes, at least i had to when i tried to use it
Get NugetForUnity to facilitate installation
Yes that one
Hey. I'm trying to replicate the way Cities Skylines draws roads, but I'm having trouble getting the mesh to update when each section is constructed. You can see it debug logging the number of triangles that should be in the mesh, but after assigning that mesh each time a section is finished to the MeshFilter.mesh it's not updating. Any idea what I'm missing? Doing this at runtime.
system
Hey, so my team and I was wondering if there are any ways to completely exclude the Unity modules and libraries from an assembly? We are running into the issue where we are trying to keep our core completely separate from Unity, as to where you could in theory run the core scripts in pure c#. However, this proves a bit difficult. I've looked into the "No Engine Reference" option in assembly definition assets, but even with this option, I am still able to use things like Vector3 from the UnityEngine namespace. Any suggestions to how to achieve this (besides just not using the namespace ofc)?
Did you try to compile by making a build ?
It would be really suprising that the functionnality is not working.
Alternatively, you might want to code the whole thing outside of Unity and make a DLL.
There is also static analysis/linter tool which could potentially help. (I've not found documentation relevant to your specific issue, however I know it can be done)
You could also just do a Unit Test that check if there is any using Unity... in any files that has been commited.
float flashlightRotation = 0f;
void Update(){
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
flashlightRotation += mouseX;
//Rotating flashlight object with player
flashlight.transform.Rotate(0,flashlightRotation,0);
}
so I'm trying to have my flashlight(which is a child of my player)to rotate with him when he turns on the x axis, but when I start my game the flashlight just starts spinning uncontrollably.
using UnityEngine;
using System.Collections;
// Performs a mouse look.
public class ExampleClass : MonoBehaviour
{
float horizontalSpeed = 2.0f;
float verticalSpeed = 2.0f;
void Update()
{
// Get the mouse delta. This is not in the range -1...1
float h = horizontalSpeed * Input.GetAxis("Mouse X");
float v = verticalSpeed * Input.GetAxis("Mouse Y");
transform.Rotate(v, h, 0);
}
}
You are rotating each frame the value of flashlightRotation which increment continuously.
ah i see, but whats the difference with this new code ?
Also:
This is frame-rate independent; you do not need to be concerned about varying frame-rates when using this value.
https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
Read it. The code is as simple as it can be done.
It will be a good exercice.
Hi. One question, what would be the best way to make an animation curve that all objects can use/reference without having to manually assign that curve to all of them please?
scriptable object probably
and how do I reference that scriptable object without having to manually set it in the inspector please? Or that isn't possible?
like reference it within a script?
https://twitter.com/t3ssel8r/status/1582256387685433345 here's the approach I had in mind. It should work for an animation curve too
Relatively painless way of implementing a library of prefabs/assets that's shared across a #unity3d project, without having serialized references all over the place:
189
yea the same problem is happening
my old code was basically identical to this
but Im not even rotating my mouse, so I dont understand why the flashlight is rotating.
suppose your car is moving at 30 miles per hour
it doesn't matter if your foot isn't on the gas
it's going to keep moving forwards...
flashlight.transform.Rotate(0,flashlightRotation,0);
this does not set the rotation
it applies a rotation
if you do flashlightRotation += mouseX; then it'll add the current x position of the mouse to the rotation each frame
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Flashlight_Rotation : MonoBehaviour
{
private float sensX = 200f;
private float sensY = 200f;
// Update is called once per frame
void Update()
{
float h = sensX * Input.GetAxis("Mouse X");
float v = sensY * Input.GetAxis("Mouse Y");
transform.Rotate(v, h, 0);
}
}
so this is setting a rotation?
It's adding rotation
this is applying a rotation each frame -- but it's only applying the rotation from your latest mouse input
instead of adding up all of your mouse inputs and applying those every frame
you have two options
1: add up all of your inputs and set the rotation
2: don't add up your inputs and add a rotation
you are adding up your inputs, then adding a rotation
that is wrong.
so how would I set a rotation?
something like
transform.localRotation = Quaternion.AngleAxis(yaw, Vector3.up) * Quaternion.AngleAxis(pitch, Vector3.right);
where you add to yaw and pitch each frame
i think that behaves differently than
transform.localRotation = Quaternion.Euler(pitch, yaw, 0);
iirc euler does Z, then X, then Y; so it would pitch up and down and THEN yaw left and right
but don't quote me on that; I need to go check...
i'd just stick with that tbh
my code doesn't currently work, so I don't think thats a good idea lol
why are we multiplying the x and y axis inputs here tho?
wouldn't we want it to be separate ?
in what way does it "not work"?
multiplying two quaternions combines them
this rotates around the vertical axis, then around the sideways axis
when I start my game without moving my mouse the flashlight rotates uncontrollably
I dont understand why because this is literally the same code in my camera rotation script
3d rotation is surprisingly complicated, and uses quaternions, which are 4-dimensional hyperspheres, they're needed in order to prevent gimbal lock
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
playerCamera code - https://gdl.space/fulemayawi.cpp
and this is all of my flashlight script
also I tried to implement this and it didn't work.
your camera code is multiplying by deltaTime
that is wrong for mouse input
if you're using the same sens values for the camera and the flashlight, then the flashlight will be way too fast
since multiplying by deltaTime divides the value by your framerate
get rid of deltaTime from the camera code and reduce the sensitivites on both by a factor of like 100
also, notice how, in the camera code, you're setting the vertical rotation
cameraVerticalRotation -= mouseY;
cameraVerticalRotation = Mathf.Clamp(cameraVerticalRotation, -90f, 90f);
transform.localEulerAngles = Vector3.right * cameraVerticalRotation;
that's valid
compare that to what you were doing on the flashlight: calling transform.Rotate with the added-up inputs
player.Rotate(Vector3.up * mouseX);
this calls Rotate, but only with the most recent input, which is also valid
Just out of curiosity does anyone know why a character controller . Transform . Position to a new transform.position only would work in the fixed update method rather then a normal update method?
Because the CC overwrites the position otherwise
Either disable the CC before teleporting, or use Physics.SyncTransforms after the teleport
FixedUpdate happens right before Unity's natural physics.synctransforms call
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
oh my bad
Hello everyone!
Im trying to make a system out of the new input system of unity to rebind the controls of my game.
The main issue im working on is to disable duplicate keys.
The rebinding works normaly for every keys exept the main control keys (w a s d) and i sort of know why but dont know how to fix it.
My theory is that the keys are kind of composites but im trying to use them as just bindings for my rebinding system. The issue is that i dont know how to make them "not composite" because the new input system wants them together for vertical and horizontal axes movement, and im trying to bind the keys separately.
The rebind system in question : https://gdl.space/ipemuhudib.cs !
Thanks a lot !
isComposite = false; if that's what you need
public class Flashlight_Rotation : MonoBehaviour
{
public float sensX;
public float sensY;
private float flashlightVerticalRotation = 0f;
private float flashlightHorizontalRotation = 0f;
// Update is called once per frame
void Update()
{
float h = sensX * Input.GetAxis("Mouse X");
float v = sensY * Input.GetAxis("Mouse Y");
flashlightVerticalRotation -= v;
flashlightHorizontalRotation += h;
transform.localEulerAngles = Vector3.right * flashlightVerticalRotation;
transform.localEulerAngles = Vector3.up * flashlightHorizontalRotation;
}
}
that won't give you any vertical rotation.
and its not syncing with my camera rotation
tbh
just make the flashlight copy the camera rotation
it shouldn't get out of sync if you implement it right, but it'll have to behave exactly like the camera does or it'll drift away
transform.forward = Camera.main.transform.forward
is it possible that i use a composite like wasd individualy like one key at a time with a button with isComposite = true; ?
is .forward for any direction?
so i reference my camera in my flashlight script then write that line of code ?
nope.
Transform.forward is the forward direction of a transform.
so transform.forward is your own forward direction
so its not possible at all to use the wasd separately ?
yes but would it account for all my rotations of the camera ?
yes, because it's the forward direction of the camera's transform
that's the entire point
wait, stop, what does "individually like one key" mean?
you can also assign to forward to rotate the transform to match a direction
transform.forward = Vector3.forward; would make you face in the +Z direction
transform.forward = camera.transform.forward;