#archived-code-general

1 messages Β· Page 123 of 1

steady moat
#

In fact, I have done that yesterday lol.

#

Dont know why

#

You need to use Matrix4x4.MultiplyPoint3x4 after.

#

With the inverse if I am correct.

rough sorrel
#

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

tawny elkBOT
#
Posting 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.

steady moat
#

I would have used your code to give an example.

#

However, you made a screenshot, and now I cant 😦

rough sorrel
#

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?

steady moat
#
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);
    }
rough sorrel
#

okay thank you so much

fervent furnace
#

the Bool=true or =false

steady moat
#

fix.

rough sorrel
#

and why am I getting an error with the vectors please?

steady moat
#

Retry with the version I fixed

fervent furnace
#

error likes "the parameters must be compile time constant"?

rough sorrel
#

yeah

fervent furnace
#

then you may consider function overloading

steady moat
#

try default(Vector3)

fervent furnace
#

i forgot the default operator..

steady moat
#
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);
    }
rough sorrel
#

okay that solves the error, thanks πŸ˜„

simple egret
#

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

steady moat
#

The name parameter is even worst.

simple egret
#

You could have a single parameter of type object, or use overloads

simple egret
#

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

rough sorrel
#

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

simple egret
#

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.

misty reef
#

That worked, thank you πŸ™‚

vital bay
#

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?

vital bay
#

yep

steady moat
sleek bough
#

@vital bay Don't cross-post. And is this a question even?

rough sorrel
#
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?

vital bay
sly shoal
#

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?

steady moat
sly shoal
#

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

tawny elkBOT
#
Posting 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.

sly shoal
#
    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;
        }
    }
rain minnow
rough sorrel
sly shoal
#

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

steady moat
#

This is kinda strange the way you have done it. Usually, I do everything in an Update loop.

rain minnow
#

this isn't strange. they're using events with the new input system . . .

steady moat
#

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.

rain minnow
#

the event is invoked when the button is pressed or held (depedns how they set it up) . . .

steady moat
#

Which is when in relation to the update loop.

#

After the update or before.

#

It can matter.

latent latch
#

Inputs from the events usually happen before the updates in the next frame

steady moat
#

Then, the issue is that isnt ?

#

The one frame true.

#

It jumps before it checks ?

sly shoal
#

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

steady moat
#

I'm still waiting for the whole code though.

#

The ground check.

heady iris
#

share the entire script that handles player movement.

sly shoal
#

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;
    }```
steady moat
sly shoal
#

check if ive jumped recently in the ground check?

steady moat
#

I have jump in the last 0.1s ?

#

If you have jump recently, you are not grounded

sly shoal
#

well i have that in the input handler. is there a difference if i put it in the actual grounding check?

steady moat
#

Otherwise, you will instantiously be consider grounded (Jump has finish)

sly shoal
#

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

steady moat
#

I mean, you said your error was that IsGrounded was true after you jumped for a split second.

#

Reseting your whole jump counter

sly shoal
#

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

steady moat
#

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.

sly shoal
#

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);
    }```
steady moat
#

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);
    }
sly shoal
#

ill see if i can cause the bug again

steady moat
#

wait no.

sly shoal
#

yeah hehe something's gone wrong. it's not deducting jumps now.

#

i think its the < symbol

steady moat
#

Yeah

#

Maybe

#

I suck at boolean operation

sly shoal
#

nope not that

steady moat
#

I do not know, but you definitly need the concept of if you jumped recently in your ground check.

sly shoal
#

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

steady moat
#
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);
    }
sly shoal
steady moat
#

I do not know them, your code is kinda spread out. Use logs and breakpoint and you gonna figure it out.

sly shoal
#

yeah. i might just need to throw in a bunch of breakpoints to see exactly why its returning true for the grounding check

ivory pasture
#

how do i save a character's transform to another scene?

steady moat
ivory pasture
#

do i need a main scene to parent both scenes or no?

dusk apex
#

Also, what do you mean by save? Transfer the object to the next scene or just copy the position, rotation and scale?

ivory pasture
#

the former

dusk apex
steady moat
#

Can you post your code ?

tawny elkBOT
#
Posting 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.

tiny reef
#

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?

steady moat
#

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

tiny reef
steady moat
#

What exactly are you trying to do ?

#

A state machine ?

swift falcon
#

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)

hexed pecan
swift falcon
# hexed pecan 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

steady moat
#

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.

spark flower
#

what do you guys think of this way of getting a value in a random range

#

is it better then RandomRange()

hexed pecan
#

Seems like Random.Range with extra steps πŸ€·β€β™‚οΈ @spark flower

spark flower
#

isnt it better

steady moat
#

Alright, I will make a suggestion on how you could handle your StateMachine and you will say what does not work for you.

somber nacelle
hexed pecan
rigid island
#

^

spark flower
#

more performant

#

you get a ranbdom value betwean 0 and 1

#

vs 0 and 1000

rigid island
#

are you just guessing that is the case?

spark flower
#

yes

leaden ice
#

Definitely not more performant

somber nacelle
# spark flower vs 0 and 1000

how would that be "more performant" bigger number does not mean less performance. int and float take up exactly the same number of bytes

spark flower
#

i dont know

#

you tell me

hexed pecan
#

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

spark flower
#

well im open for knowledge

tiny reef
#

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

somber nacelle
harsh bobcat
#

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?

steady moat
#

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();
  }
}
somber nacelle
harsh bobcat
rigid island
tiny reef
rigid island
#

show its inspector

tiny reef
rigid island
# tiny reef

thats weird...
are those the tiles placed and is ok if you remove the color part?

tiny reef
#

when i remove the color part everything is fine

steady moat
#

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.

tiny reef
#

i just get my normal tilemap

#

but with the color its just all black

rigid island
tiny reef
rigid island
#

otherwise that blue might be mixing with red, causing it to look black

#

although is prob really dark purple

tiny reef
#

red and blue mixes to black

rigid island
#

red and blue make purple

fervent furnace
#

try change the color of your tilemap renderer to white and see if the tile is red

tiny reef
#

ill try

tiny reef
#

so the setColor is adding color?

#

hm just to the base color

#

well everything works now thx

steady moat
#

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.

rigid island
#

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

placid rampart
#

Hello everyone, tell me where in two scenes 175 mb?

tiny reef
#

yes

#

thanks

low horizon
#

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?

steady moat
placid rampart
hidden parrot
fervent furnace
#

if you need unity api (except debug.log) then "no" ways for you to multithreads

steady moat
fervent furnace
#

or you can have a look to job system

steady moat
#

Also, Font is treacherous.

placid rampart
steady moat
#

To find out what is included that you are not expected.

swift falcon
#

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?

heady iris
#

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

swift falcon
#

How do I check if a savefile is corrupt?

heady iris
#

so that you don't wind up with three corrupted save files if the user repeately alt-f4's the game lol

leaden ice
#

Use try/catch

heady iris
#

indeed

#

an invalid save file should cause an error

low horizon
heady iris
fervent furnace
#

1000 iterations seems not much....

low horizon
#

im going to run that 1000 iterations for each enemy

#

and it creates spikes

swift falcon
#

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

burnt gyro
#

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)

low horizon
#

not verynoticeable rn

fervent furnace
#

you can use multithreading

low horizon
#

but probably will be when i have many enemies

heady iris
#

the Jobs system may be relevant for you

#

it lets you do work on other threads (possibly over many frames)

fervent furnace
#

then you need to limit the search space, consider hierarchical search, i am working on it

rigid island
low horizon
fervent furnace
#

you propably need to implement a minheap for this

heady iris
#

oh yeah, those are relevant for pathfinding algorithms, aren't they

#

PriorityQueue comes in a newer .NET version than unity provides

fervent furnace
royal pulsar
#

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?

steady moat
#

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.

heady iris
#

ah, I see

steady moat
#

Maybe he has armor ? Or he has a buff that reduce knockback ?

heady iris
#

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

royal pulsar
#

i'll look into tell dont ask, thank you

heady iris
#

you're already halfway there

#

you tell the Health object to take damage

#

rather than just subtracting from a float

royal pulsar
#

i'm struggling to conceptualize this tell dont ask stuff, im new to oop :/

royal pulsar
heady iris
#

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

royal pulsar
#

Aaah ok, thank you, that makes sense. Only bit I'm confused about now is which script handles that last functionality

royal pulsar
steady moat
# royal pulsar Aaah ok, thank you, that makes sense. Only bit I'm confused about now is which s...

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)

steady moat
#

Something like Hittable.

#
if (collision.gameObject.TryGetComponent<Hittable>(out Hittable hittable))
  hittable.TakeHit(...);
royal pulsar
#

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)?

steady moat
#

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.

royal pulsar
# steady moat Hittable would not know what is a player.

[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?

steady moat
#

Exactly

royal pulsar
#

brilliant, thanks, i understand now

static matrix
#

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

heady iris
#

if you want occlusion culling, you need to bake it

#

unity pre-computes it

hexed cipher
#

Hello, is there an alternative to Screen.currentResolution.refreshRate?

static matrix
#

...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

hexed cipher
# heady iris why?

Screen.currentResolution doesn't work in some cases, and I need information about the current refresh rate.

static matrix
#

what is this? What does it do? and can I optimize it

heady iris
#

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

static matrix
#

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

heady iris
#

is this HDRP?

static matrix
#

no

heady iris
#

then what is it?

static matrix
#

generic pipeline

heady iris
#

huh, that sounds odd.

#

i'm not very familiar with profiling rendering cost

static matrix
#

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

heady iris
#

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

static matrix
#

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

heady iris
#

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

static matrix
#

ah
how do i
not be gpu bound

#

or is that a term for the condition

heady iris
#

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

static matrix
#

ah

static matrix
#

where do I do that

heady iris
#

see the Quality section of your project settings

#

you might try just switching the quality level

static matrix
#

to a lower one?

heady iris
#

these are the HDRP ones

static matrix
#

ahhh

heady iris
#

the built in RP has a different list

static matrix
#

let me check

heady iris
#

double click one to make it the default, iirc

static matrix
#

ahh

#

ok

#

let me try that

heady iris
#

I know that switching from High Fidelity to Performant doubled my FPS on my macbook

static matrix
#

that did not work!

#

nothing changed!

#

yay!

#

ill work on it later

slim latch
#

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.

dusty umbra
#

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!

heady iris
royal pulsar
#

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);
        }
    }
}
hard tapir
#

Will this work?

#

handAnimator.runtimeAnimatorController["R"] = RA;

#

I need to replace R animation in hand animator by RA animation clip

leaden ice
#

This is the exact use case for it

hard tapir
steady moat
# royal pulsar ``` using System.Collections; using System.Collections.Generic; using UnityEngin...

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.

haughty bobcat
#

Im gonna see if this solves the issue

#

It works but why it looks like a star instead of a cone?

royal pulsar
steady moat
haughty bobcat
#

I got a little help from chatgpt but seems it messed up a bit

steady moat
#

I was wondering why the heck did you comment every line in spanish also.

haughty bobcat
#

I know coding

#

Im spanish

steady moat
#

Knowing coding and knowing what you are doing are seperate things.

#

Most people comment in english same if their native language is not.

haughty bobcat
#

whatever still how I can fix the rays

steady moat
#

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.

haughty bobcat
#

I dont know math -.-

steady moat
#

There is no math there.

#

Only logic.

haughty bobcat
#

Yeha there is

steady moat
#

Are you saying that a single division is math ?

haughty bobcat
#

Just tell me how to fix it and stop complaining

steady moat
#

Ha !

#

No. I won't.

haughty bobcat
#

Okay, rude

#

This is why I dont ask for help -.-

paper heart
#

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?

royal pulsar
# steady moat Usually you want to merge the concept of hitting and knockback. However, it can ...
{
    [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

steady moat
royal pulsar
#

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

twin hull
lavish ridge
#

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?

heady iris
#

just put the class first

ashen yoke
#

if(varname is IInterface ivar)

heady iris
#

oh wait

#

i thought you were talking about a class declaration

#

yeah, just check both in sequence

ashen yoke
#
            float a = 5;
            if(a is IComparable icomp && icomp is float f)
            {

            }
weary rose
#

how do I make it so that when I move my cinemachine camera, the player's turn is delayed?

lavish ridge
steady moat
#
public class MyClass : MonoBehaviour, IInterface
#

?

lavish ridge
#

Like I'm another script.

MonoBehaviour IInterface ClassName;
ashen yoke
#

you can implement as many interfaces as you like

lavish ridge
#

What would be valid syntax?

steady moat
#

It is one of the other. Then you cast the other in what you want.

ashen yoke
#

the one Simferoce posted

lavish ridge
steady moat
#

No. You need to choose one or the other.

lavish ridge
#

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

steady moat
#

You could alternatively combine both in an other class.

public class MyInterfaceMonoBehaviour : MonoBehaviour {...};
public class MyObject : MyInterfaceMonoBehaviour {...};
lavish ridge
#

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

lavish ridge
ashen yoke
#

it hides

#

hiding and overriding are different things

steady moat
lavish ridge
#

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

steady moat
#

I'm not sending those links for fun.

ashen yoke
#

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

lavish ridge
# steady moat What you are doing is: https://learn.microsoft.com/en-us/dotnet/csharp/language-...

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)

steady moat
#

Also, you are using static.

lavish ridge
#

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

ashen yoke
#

statics are unique per type, static type of a type is a separate thing

weary rose
steady moat
#

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);
    }
weary rose
ashen yoke
#

rename to mp4 and repost

ashen yoke
#

just in this case only one type will be generated

#

nah, 2

#

since you provided generic arg

steady moat
#

You can do all sort of funcky things with that. Not really something you should do to be honest.

steady moat
ashen yoke
steady moat
#

Yes, it will.

#

It just removes the need to actually do it yourself.

#

I mean, it will only generate MyClass<float> ?

ashen yoke
#

no, MyClass is a unique class

#

i confused myself you are correct

#

but only for the non static

#

both will generate separate unique statics

steady moat
#

You gonna only have 1 version of GetValue at the end because we only provide 1 version of MyBase<T> which is MyBase<float> ?

ashen yoke
#

no

lavish ridge
#
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?

ashen yoke
#

both MyClass and MyClass<float> will have their own unique GetValue

steady moat
ashen yoke
#

a non static class cant inherit static properties since static classes cant be inherited

steady moat
ashen yoke
steady moat
#

If you do MyClass2 : MyBase<float>. You gonna have 2 GetValue.

#

Both there is no GetValue inside MyBase<T>

#

It is only a template

ashen yoke
#

it will generate it

#

thats what generics do

steady moat
#

If you do not provide the (T), it wont.

ashen yoke
#

but you did provide it

steady moat
#

The only provided (T) is from MyClass

ashen yoke
#

MyBase<float>

#

this will generate MyBase<float>

lavish ridge
ashen yoke
#

which is a separate type

steady moat
#

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.

steady moat
#

Everything you want is there.

#

You can use Youtube also, if you prefer.

ashen yoke
#

most likely you want to use a virtual method

lavish ridge
#

im familiar with polymorphism; im just new to c#

steady moat
#

Then, learn polymorphism in c#.

#

It is going to be fast.

#

If you already know the concept.

hollow falcon
#
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?

twin hull
ashen yoke
#

@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
lavish ridge
#

virtual methods did the trick; thanks for the help yall

ashen yoke
steady moat
# hollow falcon ```[Serializable, StructLayout(LayoutKind.Explicit)] public partial struct TTT :...

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

swift falcon
#

whats

hollow falcon
#

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

steady moat
#

True The callback interface only works with classes. It does not work with structs.

hollow falcon
#

Can i somehow copy the struct from property to a new object, edit it and apply back to main object?

weary rose
steady moat
#

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.

weary rose
hollow falcon
#

How do i do it?

hollow falcon
steady moat
weary rose
upper badge
#

Did you try rotating the body by 90 degrees?

hollow falcon
steady moat
#

Curious, I guess it does not know how to handle things.

#

The obvious choice would be to rething your architecture.

hollow falcon
#

I`m creating a polymorphic struct system for ECS

steady moat
#

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

hollow falcon
#

i really need it

steady moat
#

ECS is Data-Oriented and GameObject is OOP

hollow falcon
#

My game is super complex and it is the best way to handle some things

steady moat
#

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.

ashen yoke
#

thats a union

hollow falcon
#

It is working on my game

#

it is a tagged union

ashen yoke
#

union is just struct abuse

#

not polymorphic

hollow falcon
#

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

wild rose
#

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

somber nacelle
#

c does not exist in that context because it is declared inside of Start so it's scope is only within Start

rain minnow
wild rose
#

and it will work

#

or do I also include "Color c = Cam1.color;"

weary rose
somber nacelle
wild rose
#

oh yeah true

limber agate
wild rose
#

ok thanks

#

im getting a bunch of red

somber nacelle
#

= is assignment == is to compare

limber agate
#

i dont think its that

wild rose
#

also ignore the Ws

#

those are meant to be cs

leaden ice
rain minnow
limber agate
#

no ik its that

#

but i feel like its also something else

leaden ice
#

Colors won't have a value of 100

#

They're 0-1

#

No

limber agate
#

255

leaden ice
#

Rgba are all 0-1 with color

#

With color32 it's 0-255

wild rose
#

so do I do Color c == Cam1.color;?

limber agate
#

yes

leaden ice
#

No

wild rose
#

im dumb okay

leaden ice
#

That's an assignment

wild rose
#

i am the ape brain level of coding

leaden ice
#

Assignment is =

wild rose
#

okay that makes sense

limber agate
#

where it says imput getbutton down

#

in a if statement your comparing

#

your not setting

wild rose
#

this is what im with rn

limber agate
#

so its if( something == something)

wild rose
#

ok

#

so c.a == 0

limber agate
#

in the if staments change it to ==

wild rose
#

in the if

#

got it

limber agate
#

yes

primal wind
#

Why is it red

limber agate
#

cuz its wrong

primal wind
#

Oh yeah =

limber agate
#

whys the c red

wild rose
primal wind
#

Didn't see it the first time

wild rose
#

i still have some red cs

rain minnow
limber agate
#

is c still declared in start

#

bro

primal wind
leaden ice
primal wind
#

Oh yeah

limber agate
#

ur declaring the same variable 3 times

#

only declare it outside of the if

wild rose
#

ok i fixed it

limber agate
#

does it work now

wild rose
#

declaring it multiple times was the issue

limber agate
leaden ice
#

It's still missing the reassignment

#

Cam1.color = c; probably missing

steady moat
wild rose
#

its not working

leaden ice
#

Also yes still have 100 instead of 1

limber agate
#

just setactive(false)

leaden ice
#

That too

limber agate
#

image.SetActive(true/false)

#

way simpler

wild rose
#

setactive doesnt work for me

#

idk why

limber agate
#

it doesnt just not work

wild rose
#

it just doesnt act like its a thing

steady moat
wild rose
#

but I cant figure it out

limber agate
#

gameobject.SetActive

#

u cant just use SetActive

wild rose
#

yeah ik

limber agate
#

transform.gameobject.SetActive(true);

#

what is the script on

#

is the script on the object your trying to become visible./invisible

wild rose
#

okay wait so do i do the input stuff, and then && transform.Cam1.SetActive(true/false)?

limber agate
#

so what are you trying to do

#

ill rewrite the script rq

wild rose
#

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

limber agate
#

ok 1 sec

hollow falcon
weary rose
#

is my question for beginner or general?

wild rose
limber agate
wild rose
#

oh i didnt see the reply thing

#

im dumb

limber agate
weary rose
wild rose
limber agate
wild rose
#

ok

#

sounds good

weary rose
limber agate
wild rose
#

yay

limber agate
#

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);
        }
    }
}```
wide barn
wild rose
#

I would establish game object as cam1 first right

limber agate
#

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

wild rose
#

ok okay

#

unityengine.inputsystem is red

weary rose
limber agate
#

oops i made a mistake

#

i forgot if a gameobject is inactive

wild rose
limber agate
#

the scripts arre disabled

#

hance you cant re enable it

#

u need to download input system

wild rose
#

how and where do I do that

#

is that in the package manager

limber agate
#

window -> package manager -> input system

weary rose
#

@wide barn even when I rotate it, it still looks to the side

wild rose
#

ok thanks

#

so you said there was a mistake in that code?

limber agate
# wild rose ok thanks
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

wild rose
limber agate
#

i didnt test it so lmk if it doesnt work

wild rose
limber agate
#

delete the using statment that doesnt work

#

and still see if it still works

#

click x there

wild rose
#

ok

#

ill try that code now

weary rose
#

bro this thing is so annoying

#

why cant my player just face the right way!

wild rose
#

input system is still red

#

i restarted visual studios

limber agate
#

they save unity engine

#

download input system

#

and click yes

wild rose
#

ok

#

i didnt get an option to this time

limber agate
#

good

wild rose
#

inputsystem is still red tho

limber agate
# wild rose i didnt get an option to this time
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

wild rose
#

should I restart unity to fix the ".InputSystem" being red?

#

or what

limber agate
#

u got to make a input system

#

i think

#

show me the error

#

and what it says

wild rose
#

so this code is good?

#

oh

limber agate
#

yes thats good

wild rose
#

so when eventsystems was inputsystem

#

it wss underlined red

#

swiggled line

limber agate
#

why are u using eventsystem

#

events are for UnityEvents and such

lethal tusk
#

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

limber agate
wild rose
limber agate
#

great tutorial

#

just copy the code i sent u and just show me the error

lethal tusk
wild rose
limber agate
#

yes

wild rose
#

input system is red

limber agate
weary rose
#

let me know when you guys are done

wild rose
#

it says remove not install

limber agate
#

rightclick create inputactions

wild rose
#

ok

#

now what

limber agate
#

not see if it works cuz i honesly idek anymo

#

❗ Daily reminder to backup your projects ❗

wild rose
#

inputsystem is still red

limber agate
#

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

wild rose
#

i just deleted the input system and it worked

#

like removed it from the code

#

thanks for the help

limber agate
#

thats wierd

weary rose
#

ive tried rotating the player but no good

limber agate
weary rose
#

the player faces to the the side when moving forward

#

its always facing 90 degrees in the wrong direction

limber agate
#

seeing your code would be helpful

limber agate
leaden ice
limber agate
#

or that

weary rose
leaden ice
#

In blender

#

Or give it an empty parent object and fix it like that

weary rose
#

how would I do that

primal wind
#

Right click > Create Empty Parent

#

Or make an empty object then set the object as it's child then rotate it

weary rose
#

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

soft shard
#

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);
light rock
soft shard
# light rock ~~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

light rock
#

so its applying correctly but its just doing it at the end of the frame (after your log statement)

half steppe
#

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

soft shard
lethal tusk
#
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();
ashen yoke
#

missed the rest sorry

ashen yoke
#

since you put it in a namespace

broken fractal
lethal tusk
ashen yoke
#

SaveLoadSystem

lethal tusk
#

oh tha name space?

ashen yoke
#

it says namespace

lethal tusk
#

yeah namespace

broken fractal
lethal tusk
ashen yoke
#

show code

lethal tusk
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SaveLoadSystem;

public class ButtonManager : MonoBehaviour
{
    public void ClickSave1()
    {
        SavaDataManager.Save();
    }
}
ashen yoke
#

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

tawny elkBOT
#
πŸ’‘ IDE Configuration

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.

lethal tusk
#

It draw a red line under SaveDataManager says does not exist in the current context

crude mortar
#

It could be in an unreferenced assembly, if you are using assembly definitions.

ashen yoke
#

yes because you have a typo

lethal tusk
#

no my ide is fine, I use it for a long time on other projects

ashen yoke
#

use ctrl + space to autocomplete

#

will help avoid typos

soft shard
# ashen yoke its works in windowed

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());
        }
    }
lethal tusk
#

there wasn't any typo but It showed as a typo til I use autocomplete, Weird

#

thanks a lot guys

ashen yoke
#

Sava as i said earlier

#

you ignore a lot of whats said it seems

lethal tusk
#

no no I did save both scripts

crude mortar
#

no, they are saying you spelled it Sava when it should be Save

#

as shown in the screenshot

lethal tusk
#

oh im so stupid

#

thats embarrassing

ashen yoke
#

intellect has nothing to do with it

#

programmers develope the habbit of really paying attention over long time

lethal tusk
#

myabe its beacuse its like 3am here lol

quartz folio
#

that's the stupid part, go to sleep πŸ˜›

lethal tusk
#

will do

graceful patio
#

webGL builds. of your code
is it possible to read text files in a WebGL build

crimson mortar
#

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;
    }```
graceful patio
#

if anyone can solve my problem

#

thank

#

you

weary rose
#

is there a way to make landing less harsh when I land after jumping

broken fractal
weary rose
broken fractal
broken fractal
#

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

cyan rapids
#

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;
    }```
tawny mountain
#

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

lethal tusk
soft shard
soft shard
# cyan rapids I seem to be generating a fair chunk of garbage (1.1kb) per frame in this functi...

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

cyan rapids
vernal compass
#

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);
    }
}`
cyan rapids
soft shard
# cyan rapids Oh thanks! I forgot about deep profile, I'll try that. Does foreach generate gar...

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

cyan rapids
snow moth
#

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

latent latch
#

Is your ide configured

snow moth
#

ye

latent latch
#

Probably want to also explain what's wrong then ;p

snow moth
#

my sprite wont jump

#

idk why

#

when i press space it dosent do anything

soft shard
mossy snow
soft shard
#

Sounds like it worked out

cyan rapids
#

Yep, now to address the other 4kb garbage per frame from other stuff. Yippee πŸ˜…

lapis nexus
#

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.

leaden ice
#

this kills all coroutines running on it (they will not resume from their yields)

lapis nexus
leaden ice
#

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)

lapis nexus
tawny mountain
#

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

weary rose
#

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

prime sinew
gray mural
#

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();
        }
    }
}
leaden forge
#

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 ?
lean field
#

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

blazing smelt
# lean field For learning purposes I am working on a tictactoe game. It's in VR (but my quest...

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.

lean field
blazing smelt
#

yeah 'actor' sounded like UE lingo

lean field
#

My bad, been switching around a lot past few weeks.

knotty sun
lean field
#

Your pieces are hidden and you have to find them before a timer runs out. It's dumb πŸ˜„

knotty sun
#

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

lean field
#

That's nasty, I love it πŸ˜„

#

Although I don't think awake gets called before I call GetComponent, or is that a syncronous process?

knotty sun
#

Awake is called immediatety after Instantiate

#

so no GetComponent required

blazing smelt
#

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)

versed loom
#

Do i have to install Microsoft.CodeAnalysis by myself?

primal wind
#

Yes, at least i had to when i tried to use it

#

Get NugetForUnity to facilitate installation

versed loom
#

or is it on asset?

primal wind
#

Yes that one

inner pine
#

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.

echo rain
#

system

cobalt apex
#

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)?

steady moat
#

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.

stark jacinth
#
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.

steady moat
# stark jacinth so I'm trying to have my flashlight(which is a child of my player)to rotate with...
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);
    }
}

https://docs.unity3d.com/ScriptReference/Input.GetAxis.html

#

You are rotating each frame the value of flashlightRotation which increment continuously.

stark jacinth
#

ah i see, but whats the difference with this new code ?

steady moat
steady moat
#

It will be a good exercice.

rough sorrel
#

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?

inner pine
#

scriptable object probably

rough sorrel
#

and how do I reference that scriptable object without having to manually set it in the inspector please? Or that isn't possible?

inner pine
#

like reference it within a script?

rough sorrel
#

yeah

#

like, without having to manually drag and drop it into the needed script

inner pine
stark jacinth
#

my old code was basically identical to this

#

but Im not even rotating my mouse, so I dont understand why the flashlight is rotating.

heady iris
#

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

inner pine
stark jacinth
#
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?

leaden ice
#

It's adding rotation

heady iris
#

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.

stark jacinth
#

so how would I set a rotation?

heady iris
#

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...

stark jacinth
stark jacinth
#

wouldn't we want it to be separate ?

heady iris
heady iris
#

this rotates around the vertical axis, then around the sideways axis

stark jacinth
#

I dont understand why because this is literally the same code in my camera rotation script

inner pine
#

3d rotation is surprisingly complicated, and uses quaternions, which are 4-dimensional hyperspheres, they're needed in order to prevent gimbal lock

heady iris
#

share your camera and flashlight scripts

#

!code

tawny elkBOT
#
Posting 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.

stark jacinth
stark jacinth
stark jacinth
heady iris
#

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

neon junco
#

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?

leaden ice
#

Either disable the CC before teleporting, or use Physics.SyncTransforms after the teleport

#

FixedUpdate happens right before Unity's natural physics.synctransforms call

gray mural
#

!code

tawny elkBOT
#
Posting 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.

boreal kelp
#

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 !

stark jacinth
# heady iris `player.Rotate(Vector3.up * mouseX);` this calls `Rotate`, but only with the mo...
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;

    }
}
heady iris
#

that won't give you any vertical rotation.

stark jacinth
#

I wrote this which rotates the flashlight on the x axis, but not on the y

#

yea

heady iris
#

you're setting localEulerAngles twice

#

of course the first rotation is lost!

stark jacinth
#

and its not syncing with my camera rotation

heady iris
#

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

boreal kelp
stark jacinth
#

is .forward for any direction?

#

so i reference my camera in my flashlight script then write that line of code ?

heady iris
#

so transform.forward is your own forward direction

boreal kelp
stark jacinth
heady iris
#

yes, because it's the forward direction of the camera's transform

#

that's the entire point

gray mural
heady iris
#

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

stark jacinth
#

transform.forward = camera.transform.forward;