#💻┃code-beginner

1 messages · Page 612 of 1

acoustic belfry
#

well, thanks a lot :3

#

btw this is a good way to reflect it, right?

    public void Parry()
    {
        Debug.Log("PARRY");
        rb.linearVelocity = -rb.linearVelocity;
        transform.right = rb.linearVelocity.normalized;
        parried = true;

    }```i know that "if it works, it works", but something feels...off
#

unless is ok, then im just paranoid

rich adder
#

its fine if all ur doing is reversing direction

#

mine is 3D and reflect in the direction you aim at

sand mesa
#

alright

rich adder
sand mesa
#

i wanna do something stupid; i wanna control where it is in the scene the players spawn

rich adder
#

pretty vague

rocky canyon
#

use an empty gameobject

#

"SpawnPosition"

#

instantiate(prefab, SpawnPosition.position, Quaternion....)

sand mesa
#

roger

#

Uno Momento

nocturne hemlock
#
public class Typewriter : MonoBehaviour
{
    public bool canmove;
    public string dia;
    [SerializeField] TMP_Text d;

    public IEnumerator Speak(string[] wsaid)
    {
        canmove = false;
        d.text = "";
        for (int e = 0; e < wsaid.Length + 1; e++)
        {
            d.text = "";
            for (int i = 0; i < wsaid[e].Length; i++)
            {
                d.text = d.text + wsaid[e][i];
                yield return new WaitForSeconds(0.05f);
            }
            yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Z));
            if(e == wsaid.Length)
            {
                yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Z));
                canmove = true;
            }
        }
    }
}
``` is this a good typewriter effect or should i make changes
rich adder
#

if its working how you want then its fine

#

would probably opt for not using magic numers

#

yield return new WaitForSeconds(0.05f);
yield return new WaitForSeconds(timeBetweenChar);

slender nymph
#

rather than allocating a new string each iteration of the loop, you should instead assign the entire string to the TMP_Text object then just modify the maxVisibleCharacters property

nocturne hemlock
#

just want it to be optimized :)

nocturne hemlock
#

i was locked in for a sec lmao

rich adder
#

when TMP is not an option, can also use StringBuilder iirc much better than new string

slender nymph
#

string builder wouldn't really make much difference in this scenario because it would still need to allocate a new string to display for each iteration of the loop

rich adder
#

yea just meant in general

slender nymph
#

another optimization to think about would be to cache the WaitForSeconds and just reuse the same instance of that instead of creating a new instance each iteration

rich adder
#

oh yeah this def ^

#

if the number is not changing you just cache

#

var waitTime = new WaitForSeconds(timeBetweenChars); //before loop

yield return waitTime; //inside loop

nocturne hemlock
#

okay i see how it works ty so much

#

im learning

rich adder
rocky canyon
#

yield return oneSecondWait

cosmic dagger
#

Exactly; the only way to do it . . .

rich adder
#

nested while loops is the way XD

#

I hardly find myself using any Yield Instruction anymore

sand mesa
#

quesiton; how can I arrange it so
DontDestroyOnLoad();
refers to itself

eternal star
#

Hi, I think my Unity file is corrupted, and I'm getting a "BuildProfileContext" error. How can I create a new project and transfer my files?

naive pawn
sand mesa
#

the gameobject holding the script itself won't be destroyed on load

naive pawn
#

DontDestroyOnLoad(this) or DontDestroyOnLoad(gameObject)

sand mesa
#

roger roger

rich adder
#

basically
gameObject is the entire object
this is the script/component

#

in DDOL that means the whole object anyway

eternal star
#

Can you also help with backups? How do you create backups?

rocky canyon
ruby zephyr
#

Do you guys think it's good to make small games like flappy bird with chat gpt and make them explain how the code worked code by code? I'll ask for very deep explanations then I'll also deeply comprehend it.

polar acorn
#

You should instead use the wealth of actual knowledge on the subject from human beings with the ability to fact check, rather than the over-engineered markov chain that predicts the next word in the sentence really fast

rich adder
#

"deep explanations" is useless if its just telling you some hallucinated bullshit

#

and you as a beginner wont know when its hallucinating

#

its also not guarateed you get suggested the best method / less cumbersome or efficent way to do something

ruby zephyr
#

Okay, I'm afraid I don't have the developer mindset that every youtuber is talking about yet.

So.. Do you guys then know the most effective way of learning?

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

rich adder
#

what youtuber ? why are you listening to youtubers

ruby zephyr
#

As I think I am stuck in a tutorial trap where I have already watched a hundred tutorials about programming and unity yet I don't know what they are for.

rich adder
#

there is a difference between incrementing your knowledge step by step only moving onto the next thing when you actually know how to use what you learned, and just following / copying

ruby zephyr
rich adder
#

motivation to me comes with pursuing new knowledge / learning new thing

#

you ideally copy code once you understand what each line does

#

even just learning small bits, you dont have to "make a small game" in the beginning.
even just doing simple C# learning through console apps will help you understand basic coding concepts

#

personally after a while it was easier to just learn C# without slapping all those unity APIs/concepts in

#

Unity is an API so once you learn C# on its own, you can read any APIs aside from unity.. the rest is just knowing the engine specific quirks like GameObject concepts etc

ruby zephyr
#

well I'm mostly familliar with unity's tools now since it is the first thing that I tried learning.

Should I then watch simple c# tutorials that focuses with unity?

rich adder
#

In a regular .NET /C# enviroement you're more likely to get better material

#

(aside from learn) unity tutorials are made for content views not accuracy

ruby zephyr
#

May I only focus on Unity programming for now?

#

And not about web dev and more

rich adder
rich adder
#

creating objects, methods, properties, arrays

#

etc

#

You are less likely to learn all these in Unity tutorials

#

they assume you somewhat have that knowledge already

ruby zephyr
#

Do I do hands on learning?

ruby zephyr
#

Oh okayy sorry, btw we had a long conversation already soo.. To summarize, What should I do?

rich adder
#

learning regular c# on its own, apply those concepts in unity then slowly start using unity specific methods / components

ruby zephyr
#

Alright thats nicee, thanks very muchhh 🤗

pure drift
polar acorn
pure drift
#

ok i will try that rq

hollow gyro
#

Is there a "best" way to start? or at least a preferred route?

rich adder
#

mostly where the links are

#

in a nutshel Unity learn site and Microsoft's website

pure drift
#

so i put the name of the gameobject it hit and it shows enemies but never the target gameobject

hollow gyro
polar acorn
rich adder
#

show new code

pure drift
#

yep i made sure to do that

polar acorn
rich adder
#

kinematic can still call OnCollision if the other object has dynmaic rb

polar acorn
rich adder
#

oh was replying to original Chris message they edited

naive pawn
pure drift
#

so on the object that is moving i should have a dynamic rigid body?

polar acorn
naive pawn
polar acorn
#

You have to actually be using the rigibody to handle the movement

rich adder
#

weird..fun fact Physics2D kinematic has velocity 🤔

naive pawn
#

why wouldn't it

#

it's the same component

rich adder
#

Rigidbody 3D doesnt have velocity once its kinematic

#

it just gets reset to 0

#

in 2D doesnt work like that, it screwed me over a couple of times

naive pawn
#

huh

rich adder
#

thats why they have the "Static" flag

pure drift
rich adder
#

not at all

#

this is essentially teleporting

#

the dynamic rigidbody has to play "Catch up" every physics tic.. not good

polar acorn
rich adder
#

Rigidbody is living inside a different scene, when you omit moving the rigidbody the regular scene moves the transform while the physics is ignored

#

when you move rigidbody, the opposite happens. The rigidbody moves the Transform

pure drift
#

any tips for applying seek using rigid body

rich adder
#

applying seek?

pure drift
#

seek steering behavior

rich adder
#

most of the time you can just replace it 1-1

#

transform.position += (Vector3)(velocity * Time.deltaTime);
with
rigidbody.velocity += velocity

pure drift
#

intresting thank you

covert flower
#

so I have an issue that i was trying to fix where I would ragdoll an enemy and they would then reset to the position the started the scene in. I attempted to fix it with the code at the bottom however this made it worse. any reccomended fixes

eternal falconBOT
covert flower
rich adder
#

under it

covert flower
rich adder
rich adder
#

if health is 0 or less

#

what are you trying to Reset the positions/rotations of ragdoll you mean?

covert flower
covert flower
rich adder
covert flower
#

or where the ragdoll started instead of ended

rich adder
# covert flower nah for some reason they spawn on the parent

can you make a quick video of issue? having a hard understanding whats what since Idk the hierarchy
this looks hella sketch
Transform parentTransform = GameObject.Find("EnemyVis").transform;
Transform specificChildTransform = parentTransform.Find("mixamorig:Hips");

prime cobalt
#

How can I find out which of these values is creating an index out of bounds? I can't debug.log any of the values besides the kernel ID because the error makes the script not work after this line and this script doesn't get the values until this line. And compute shaders can't use debug.log.

wintry quarry
#

You probably don't h ave a kernel with that name?

#

Unless the index out of bounds is happening elsewhere

#

What's the actual error message say?

prime cobalt
wintry quarry
covert flower
rich adder
#

doesnt FindKerner return a string?

#

hows a string get in an index wanted in GetKernelThreadGroupSizes

wintry quarry
#

no it returns a kernel index

prime cobalt
rich adder
#

ahh yea myb my eyes are broken

wintry quarry
prime cobalt
rich adder
prime cobalt
wintry quarry
covert flower
prime cobalt
wintry quarry
#

and still has the same error?

prime cobalt
#

Yes

wintry quarry
#

but with 1 this time?

prime cobalt
#

Yep

wintry quarry
# prime cobalt Yep

Ok from what I'm reading it means you have a syntax error in your shader somewhere

#

bascically it's not compiling properly

#

so there is no kernel

prime cobalt
#

Hmm ok, good to know. Thanks furipray2

wintry quarry
covert flower
#

looks like itll fit perfectly

rich adder
#

for me once I disable animator the ragdoll falls, i just use a method to iterate through all rigidbodies limbs to set them back to active/gravity

prime cobalt
inland cobalt
#
private void Rotate()
{
    Vector2 mouseDelta = _actions["LookDelta"].ReadValue<Vector2>();
    float rollDirection = 0f;
    if(_actions["Roll Left"].IsPressed()) rollDirection ++;
    if(_actions["Roll Right"].IsPressed()) rollDirection --;

    float multiplier = Time.deltaTime * _sensitivity * 5f;

    Quaternion yaw = Quaternion.AngleAxis(mouseDelta.x * multiplier, Vector3.up);
    Quaternion pitch = Quaternion.AngleAxis(-mouseDelta.y * multiplier, Vector3.right);    
    Quaternion roll = Quaternion.AngleAxis(rollDirection * Time.deltaTime * _sensitivity * 10f, Vector3.forward);      

    transform.localRotation *= yaw * pitch * roll;
}```

Anyone know why my looking around feels jittery with a mouse, and straight up doesn't work with trackpad? I can't seem to figure it out
#

(Rotate is called every update)

#

look delta is this

rich adder
swift crag
#

That's causing it, yes

rich adder
#

delta already returns the distance between frames

swift crag
#

If a frame takes longer to render, you'll get more mouse movement

inland cobalt
#

ah i get what you mean, cheers

swift crag
#

and then you'll multiply that larger value by another larger value (since deltaTime is larger than usual)

#

thus, jitter

#

Also, rollDirection++ is going to be framerate dependent

#

You need to factor in deltaTime there

#

It doesn't matter that you multiply it with deltaTime when computing how much to roll by

#

You're going to change rollDirection at a framerate-dependent rate

inland cobalt
#

i get what you mean now, I overlooked the fact that delta is already framerate independent, thanks

#

yeah that's a whole lot smoother

sand mesa
#

alright

#

The best I can aritculate my pressing is "I wish to save the last position my player was in using a "DontDestroyOnLoad" object as that player leaves the scene, and then ensure that when I enter back into the scene, the player spawns at that position

rich adder
#

you probably use a dictionary too for each scene

#

either by name or index

#

Dictionary<string,Vector3> myPositions = new ();
string sceneName = SceneManager.GetActiveScene().name
myPositions.Add(sceneName, transform.position)
transform.position = myPositions[sceneName]

#

You can get the current scene name on scene switch event

sand mesa
#

working on it

sand mesa
#

alright

#

perfect

#

last thing; how do I see how many objects of the same type is in a scene?

#

i wanna prevent myself from making clones of instantating players

sand mesa
#

okay, sorry, ive just been using it to automatically assign references

rich adder
#

I think it searches all scenes open too so keep that in mind

sand mesa
#

well too damn bad

#

wait, HOLY THAT'S WHAT IM MISSING!

#

THANSK FOR THE INSPRIATION

sand mesa
#

right...

#

how do I make sure the code destroys the duplicates and not the original?

#

ive managed to save the original in its own little variable, but I am not sure how to format it

frank rivet
#

I have fixed smooth dampening but i still cannot figure out how to make the plane turn towards the direction the free cam is facing, any help or even sugguestions will be nice

woeful carbon
#

Has anyone here made the classic snake game but also tried incorporating rotation or curved sprites to show the snake turning cause I’m trying to do that and struggling to find a good way to go about it

rich adder
sand mesa
#

of the player

woeful carbon
rich adder
#

DDOL ?

sand mesa
#

... no...

#

i just leave the player object open....

drifting cosmos
rich adder
sand mesa
#

i made a persistent variable within the scene that records the instance of the player pawn

#

then the "player" leaves for the next scene, and when I swing back, it spawns a new player instead of using the old one

woeful carbon
sand mesa
#

and it can keep going for as long as it takes

drifting cosmos
rich adder
sand mesa
#

modularity...

rich adder
#

how?

sand mesa
#

I see now that it was HELLA dumb to constantly spawn the player object

#

... hm...

#

maybe I can just do without that code

#

one second

rich adder
#

there is no need anyway

#

spawning new one

woeful carbon
drifting cosmos
drifting cosmos
woeful carbon
#

I’ll try it out tomorrow and get back to you

drifting cosmos
#

is making an object thats of a type of one of its inherited things for generics only or is there other reasons

wintry quarry
sand mesa
#

oh god

drifting cosmos
sand mesa
#

the persistent level disappears as soon as I move to another level

#

I thought the point was it persists!

#

why does it go away?!

drifting cosmos
sand mesa
#

an object in that scene is set to that

wintry quarry
wintry quarry
sand mesa
#

this block of code is designed to ensure the level holding the instance doesnt go away

#

and is always lingering

#

except somehow it vanishes whenever I load a new level besides the one I start in

#

which kind of defeats the purpose of it being persisent

drifting cosmos
wintry quarry
sand mesa
#

no- right

sand mesa
wintry quarry
sand mesa
#

it is there once I start the game, and GONE the moment I change the level

wintry quarry
#

So you only need to write it once

wintry quarry
sand mesa
#

it is set to additive though

wintry quarry
#

Some other code is unloading the scenes then

sand mesa
#

I think I found the error

#

one second

wintry quarry
#

Or calling LoadScene without Additive

sand mesa
#

i kind of need it to be additive though

#

its got the canvas needed for fade to black and ui elements

wintry quarry
#

I didn't say not to make it additive

sand mesa
#

thats exactly what you said

wintry quarry
#

Never said that

sand mesa
#

calling Load Scene without Additive -> remove additive -> don't make it additive

wintry quarry
#

It was an extension of the thought above it:

Some other code is unloading the scenes then
Or calling LoadScene without Additive

sour fulcrum
wintry quarry
#

I'm listing things that could possibly be the problem

#

not solutions

drifting cosmos
wintry quarry
# drifting cosmos like whats the reason for making a class object of an interface it inherits is i...

Imagine this:

class Monster {
  int hp;

  public void TakeDamage(int dmg) {
    hp -= dmg;
  }
}

class Player {
  int hp;

  public void TakeDamage(int dmg) {
    hp -= dmg;
  }
}```
Now if I want to write code for an attack that can hit a player OR a Monster.,.. I have to do something like this:
```cs
void DamageTarget(object target) {
  if (target is Player p) p.TakeDamage(5);
  else if (target is Enemy e) e.TakeDamage(5);
}```

But with interfaces I can do this:
```cs
interface IDamageable {
  void TakeTamage(int dmg); // the interface only defines the "signature" of the method, not the actual implementation
}

class Monster : IDamageable {
  int hp;

  public void TakeDamage(int dmg) {
    hp -= dmg;
  }
}

class Player : IDamageable {
  int hp;

  public void TakeDamage(int dmg) {
    hp -= dmg;
  }
}```
And then I can write code like this:
```cs
void DamageTarget(IDamageable target) {
  target.TakeDamage(5);
}```
wintry quarry
drifting cosmos
#

void DamageTarget(IDamageable target) {
target.TakeDamage(5);
}
so when you write in a game object it will only work if it has Idamageable interface implemented would the takedamage have to be public if youre calling a damage target say from like a bullet object or something

wintry quarry
#

There are no GameObjects involved here

#

you cannot add interfaces or modify the GameObject class

#

only your own custom classes

#

it will only work if it has Idamageable interface implemented

#

Yes the parameter is of type IDamageable so it has to be a type that implements that interface

sand mesa
#

... right

wintry quarry
#

would the takedamage have to be public if youre calling a damage target say from like a bullet object or something
That's a totally different topic, but yes methods have to be public to be called from an outside class.

sand mesa
#

is there a way to store the last position of my player in another scene?

wintry quarry
#

Vector3 lastPlayerPosition;

#

scenes themselves don't store anything

#

you can store data on scripts that you put instances of in scenes

sand mesa
#

and that relies on the object holding the script to be constantly present, right

#

through instance

wintry quarry
#

If you want the data to stick around, the object holding the data has to stick around

sand mesa
#

the PROBLEM is that it constantly makes copies

#

whenever I load into the scene

wintry quarry
wintry quarry
sand mesa
#

thats not how you create instances?

wintry quarry
#

Everything in the scene is an instance

#

every actually instantiated object is an instance

sand mesa
#

right- instances carried over to another scene

#

that means "don't destroy on load" doesn't it?

wintry quarry
#

you are confusing the concept of an instance with that specific static variable we are calling instance which is part of a concept called "singletons". A singleton is a class for which we are guaranteeing there is only ONE instance in existence at a time. Therefore we can have a single static variable pointing to that instance

#

We typically call that variable instance because, well, it's a reference to the only instance of the class that exists.

sand mesa
#

right right right

#

so I have the variable created and it tracks where the player is

#

how, then, do I use it

wintry quarry
#

Presumably we're talking about some script that holds the player position data?

sand mesa
#

the script holding the variable gets destroyed when I load another level

wintry quarry
#

not if you use DDOL

#

you would have a DDOL singleton

#

that stores the position

#

then you access that singleton whenever you want the data on it

#

simple example:

public class MyDataHolder : MonoBehaviour {
  public static MyDataHolder Instance { get; private set; }

  public Vector3 LastPlayerPosition;

  void Awake() {
    if (Instance != null) {
      // This is a second copy. Destroy ourselves and stop the function here
      Destroy(gameObject);
      return;
    }

    // this is the first and only instance. Assign the Instance var and DDOL ourselves.
    Instance = this;
    DontDestroyOnLoad(gameObject);
  }
}

Then from any other code you can access the data with:

MyDataHolder.Instance.LastPlayerPosition```
sand mesa
#

fixed it

#

i goddamn hope

final trellis
#

the code thats causing the rror

#

oh wait

#

i just added

if (!audioSource.isPlaying)
    return;
#

nvm it diddnt fix it

#

unity error is gone, but now it still crashes

final trellis
ivory bobcat
#

Try commenting out sections to see if what's causing the crash is within this function

final trellis
#

eh i think im just gonna disable that part

#

its not a nessecary gamneplay feature

sand mesa
#

RIGHT

#

my "dont destroy on load" object is not registering in th egame itself

#

it appears to only work during editor playthrough

#

why is this the case?

edgy tangle
#

How do you determine “object is not registering”?

#

There’s any number of problems that can come with Singletons if you’re not careful, so you need to be specific about what is going wrong and when. That said though usually the problem is a race condition of some kind.

sand mesa
#

In my editor there is an object that is persisting to carry variables across levels

#

But once I built the game, it's not carrying anymore

#

Oh for crying out loud

#

I have to pricking redo the - HHHHHHHHHHHAAAAAAA

sand mesa
sour fulcrum
#

if the object isn't destroyed

short gust
#

I don't know to which channel this question goes, because it's about git lfs and googling doesn't help
I have Unity 6 with Adaptive light probes and their data is baked with *.bytes binary (and they grow quite huge)
Do I need to add them to lfs? And if so - with which attributes?
Sorry, if it's off-topic, but there literally no info about that I can find

charred spoke
#

If this is for github then if the file is above 100 mb you need to add it to lfs

north kiln
# sand mesa

This sounds like nonsense. Prefabs don't exist outside of the editor. Are you having trouble persisting a root object in a scene? Or are you using DDOL on something else?

edgy tangle
edgy tangle
sand mesa
#

Yeah I gave up

#

I just used player prefs

#

It's just positional data

sour fulcrum
#

i guess not explicitly as prefabs but

sour fulcrum
#

thats just for settings and such

north kiln
livid grail
#

Hey everyone! Ive stumbled into a very wierd bugg, it doesnt happen all the time so it is completley random...

Im using my mouse movement to open doors but somehow, sometimes my **rotation **values gets null, with is very wierd becuase it is float?

This is the error line, and the line that "rotates" the door
door.localEulerAngles = new Vector3(0, rotation, 0);

And this is how I set the rotation value

mouseValue = (Input.GetAxisRaw("Mouse X") * directionClamp ) / Time.deltaTime;
rotation = door.localEulerAngles.y;

float tempRotation = rotation + mouseValue;
rotation = Mathf.Lerp(rotation, tempRotation, Time.deltaTime);

My first guess was the mouse input value but it always returns a value, so Im currently lost

silk night
#

also in this chain rotation does not seem to be the first value to be null, set a breakpoint and check up the chain what is actually null

livid grail
#

@silk night It isnt a loop, it is a regular method that only runs when the character is interacting with a door

#

the wierd thing is that I can play and stop the game 10 times without any error occurring, then on the 11th restart it can pop up, if I restart again it is just gone...

silk night
#

i mean update loop, fixedupdate loop? otherwise your lerp doesnt make sense

livid grail
#

Ah the method is being called from Update

silk night
#

well then its time to debug, do a null check and a log in there, then set a breakpoint on the log so you only break when its actually having an error

#

(or a conditional breakpoint if you IDE supports that)

dusty geode
#

only thing that can be null on that line is door

livid grail
#

Door is not infact null, the rotation value in the inspector is set to NAN if I manually reset it to 0 it works again

#

it is the float value that returns NAN

#

debugging the rotation setup atm

red brook
#

@solar tusk

dusty geode
#

Sorry I assumed null ref exception my bad

#

Maybe post the error?

solar tusk
#

Yeah, so there is this other method. Like, 3D model it, animate it inside a modelling software. And then render the animations frame to PNG. Then make a sprite sheet for them, and use that sprite sheet animation in unity

#

@red brook

red brook
#

u can either do it 3D 2D or do 3D then bake it into 2D etc etc

solar tusk
#

I wanna do how Township did it. So what should I do

red brook
#

do you wana do exatly how they did it?

solar tusk
#

Yes. Or atleast want to know how did they do it exactly

dusty geode
red brook
#

you will never know unless you contact them

#

so write an email perhaps

#

to them

solar tusk
#

How about that

#

Sure, thanks

livid grail
#

@dusty geode Before I added the delta time the mouse input value was different on every machine an not reliable, the door sensitivity was dependent on the games FPS

dusty geode
#

It comes in as the amount the mouse has moved since last frame.

#

Also why are you lerping at all. That lerp doesn't really make sense

#

You'll never reach the target

livid grail
#

Im sure there is much better ways than my lerp but before I added the lerp the door was too snappy and had no weight to it, now it "drags" like I intended it to, so for me it works fine as it is :3

I tried to remove the DeltaTime and multiple it, both methods broke the rotation and it didnt respond to any mouse movement at all

dusty geode
#

You should remove it from the line where you are multiplying mouse by it

#

Also I would just use Quaternion.RotateTowards or Vector3.RotateTowards

livid grail
#

Im certain this is a better way than my lerp but I dont think the lerp is what is causing the NAN error

#

ive placed a lot of debugg lines atm in the code but what sucks is that the error rarely occurs 🥲

dusty geode
#

From my experience reading euler angles directly from transform can lead to unexpected results

#

have a class member variable that represents your y and modify and read that instead

#

Or do what I said and don't use euler angles and use methods that don't use them. You can rotate in other ways. Like rotate around the Y axis

livid grail
dusty geode
#

No the line where you are reading the y euler angle component from the door

dusty geode
#

@livid grail something like this

mouseValue = Input.GetAxisRaw("Mouse X");
door.Rotate(door.up, mouseValue);

#

Your problem really stems from reading directly from euler angles since multiple combinations of euler angles can represent the same rotation. Just because you set one combination does not mean you'll get the same combination back when reading from it. So either have a local Vector3 to represent euler angles that you have complete control over modifications or apply rotations without them

livid grail
#

Its wierd, Im not sure why but it only reacts whenever I stop dragging it however if I devided the mousevalue but delta time it worked whenever but the "smooth" movement wasnt present anymore

#

and yes the method is being called everyframe, I get debug logs all the time that it is being called

dusty geode
#
public float minYRotation = -45.0f;
public float maxYRotation = 45.0f;
private float currentYRotation = 0.0f;
private Quaternion initialRotation;

void Start()
{
    initialRotation = transform.localRotation;
}

void Update()
{
    float rotationSpeed = 45f;
    float rotationIncrement = rotationSpeed * Time.deltaTime;

    currentYRotation = Mathf.Clamp(currentYRotation + rotationIncrement, minYRotation, maxYRotation);

    Quaternion localRotation = Quaternion.AngleAxis(currentYRotation, Vector3.up);

    transform.localRotation = initialRotation * localRotation;
}
#

You should be able to adapt that code to your needs

#

Let me know if you have questions. You need to understand it

dusty geode
livid grail
#

Thanks! Yeah I can read that 🙂 Im just heading out tho but I rewrite it when I get back home, I really appreciate the help!

dusty geode
livid grail
queen adder
#
        var randTrigger = Random.Range(0, triggersArray.Length);
        animator.SetTrigger(randTrigger.ToString());

So the trigger name is incorrect, its something like "Parameter 0", instead of the actual string of the trigger.
And yes I did put the correct names in the array.

So why doesnt it Trigger with the correct string?

muted pawn
#

try to use

triggersArray[randTrigger]

instead of randTrigger.ToString()

#

@queen adder

queen adder
#

Yeah I tried it and it works now, thanks

muted pawn
dusty geode
# livid grail this is where I got my old solution from https://stackoverflow.com/questions/559...

Yeah that is just blatantly incorrect, even the last comment on the answer mentions the incorrectness.

Mouse input is inherently framerate independent. You can easily test this with this script on any object.

public class TestMouseRotation : MonoBehaviour
{
    [Min(10)]
    public int targetFrameRate = 60;
    public float rotationSpeed = 10;
    public float minYRotation = -45.0f;
    public float maxYRotation = 45.0f;
    private float currentYRotation = 0.0f;
    private Quaternion initialRotation;

    void Start()
    {
        QualitySettings.vSyncCount = 0;
        initialRotation = transform.localRotation;
    }

    void Update()
    {
        Application.targetFrameRate = targetFrameRate;

        float rotationIncrement = Input.GetAxisRaw("Mouse Y") * rotationSpeed;

        currentYRotation = Mathf.Clamp(currentYRotation + rotationIncrement, minYRotation, maxYRotation);

        Quaternion localRotation = Quaternion.AngleAxis(currentYRotation, Vector3.up);

        transform.localRotation = initialRotation * localRotation;
    }
}
hot harbor
#

Is there a 2d equivalent of Gizmos.Draw or is using DrawGizmos fine

hexed terrace
west radish
#

I find in general that gizmos are perfectly find for 2D use, especially as all I really need them for are circles (ie a sphere), and lines

hot harbor
#

what do you think works best?

west radish
#

just make a cube with the right size to show the rectangle boundary,

hot harbor
#

Thanks!

west radish
#

when viewed side on, a cube is exactly the same as a square

hot harbor
#

Problem was that i'm trying to do this in a statemachine that I wrote for movement, and it is not a monobehaviour so I'm currently scratching my head to figure out what to do; I came across the [DrawGizmo] attribute too

hot harbor
slender nymph
#

yeah it's a really useful debugging library and doesn't require changing or adding any logic, just a using alias and the existing physics queries JustWork™️

west radish
slender nymph
#

nah, Vertx (one of the mods) did, i just had one PR lol

hot harbor
#

I will check this out!

frank rivet
#

I got like no help at all

eternal needle
# frank rivet I got like no help at all

If your intent is to complain about that, then ok? Not everything gets responded to here. You arent promised help
Otherwise you can actually ask a question for what you need help with.

teal viper
burnt vapor
frank rivet
#

ok, sorry that I said that without bumping my message

#

here

#

bump

burnt vapor
#

Did you check if Anikki was right with their response?

frank rivet
eternal needle
# frank rivet yes but it does not give me any idea on how to make the plane turn to where the ...

use a paste site for the 2nd script, and try to narrow down which part we are supposed to look at. ngl your code is very unreadable because you're combining a lot of logic on one line (like the ternary in the SmoothDamp parameters)
for the problem of turning something to a different rotation you can use built in methods
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.RotateTowards.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.RotateTowards.html

celest shadow
#

hey all, I havent worked in unity in a hot minute and I'm picking it back up now. Things feel good but im running into an issue with "completing domain"

if I do literally anything at all, I spend 2 minutes completing domain. remove a comment? complete domain. break point? domain!

is this jsut life in unity now or can I do something?

naive pawn
#

you could turn off automatic recompilation and manually press ctrl+r to recompile/reload assets

runic lance
#

adding a break point should not cause a domain reload though
domain reload is caused either by recompiling the code or entering play mode, the latter can be disabled in the project settings

#

2 minutes seem an awful lot though, unless your project is huge or your computer very slow

celest shadow
runic lance
#

it shouldn't take more than a few seconds then

celest shadow
#

is there any feature specifically that takes a lot of work in this process? is it the few shadergraphs I've built?

shy orbit
#

NullReferenceException: Object reference not set to an instance of an object
PlayerController.ProcessInput () (at Assets/Scripts/PlayerController.cs:37)
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:18)

Why am i getting this when trying to instantiate bullets?

inland cobalt
#
private void Target()
{
    if(Physics.Raycast(_camTransform.position, _camTransform.forward, out RaycastHit hit, _maxDistance))
    {
        transform.LookAt(hit.point);
    }
    else transform.rotation = _initialRot;
}```


Hey all, im trying to get my gun model to aim at where my crosshair is pointing, so that it shoots where i expect, in my game my character is able to rotate in the y axis (roll). This code mostly works, however it also rotates the gun in this axis when i dont want it to, how can i cleanly prevent this from happening? Never really sure when dealing with quaternions
faint osprey
#

how do i reference the right value

    {
        while(progressBar.rect.xMax < 200)
        {
            progressBar.rect.x += 1;
            yield return null;
        }
    }```
i tried this but it says it cant be modified cause its not a variable
celest shadow
#

check the component on its game object and see if theres a blank space there for your prefab

shy orbit
#

no i have, its there

celest shadow
#

then you need to check the stack trace because something deeper down is null. your error doesnt tell much

runic lance
naive pawn
shy orbit
#

well this is the code i have for it

using UnityEngine;

public class Weapon : MonoBehaviour
{
    public GameObject Bullet;
    public Transform firePoint;

    public void Fire()
    {
        Instantiate (Bullet, firePoint.position, firePoint.rotation);
    }
}

and

public Weapon Weapon;
if (Input.GetMouseButtonDown(0))
        {
            Weapon.Fire();
        }
naive pawn
#
    private IEnumerator DecreaseOxygen()
    {
        while(progressBar.rect.xMax < 200)
        {
+           Rect rect = progressBar.rect;
+           rect.x += 1;
+           progressBar.rect = rect;
-           progressBar.rect.x += 1;
            yield return null;
        }
    }
```something like this @faint osprey
celest shadow
shy orbit
#

how do i do that?

shy orbit
#

the if statement is inside ProcessInput

naive pawn
#

is it that second codeblock?

#

ok

celest shadow
shy orbit
#

yeah vsc

faint osprey
naive pawn
shy orbit
#

yeah

naive pawn
naive pawn
shy orbit
#

im using vsc

naive pawn
#

check your PlayerController, have you assigned Weapon correctly?

celest shadow
# shy orbit yeah vsc

you can put a breakpoint on any line if you click the gray bar on the left side. using the green "play button" near the top will attach your visual studio to the unity process. When you call that method, you will hit the breakpoint. The editor will freeze and you can then go to vsc and inspect local values

shy orbit
#

its assigned as public Weapon Weapon;

naive pawn
#

(also btw, the variable should probably be weapon instead, so you can differentiate between the class and the variable

naive pawn
celest shadow
#

it will look like this

naive pawn
#

do you have any Weapon = ... in your script?

shy orbit
#

i dont no

naive pawn
naive pawn
shy orbit
#

no i dont, what would i put after the = tho?

#

just weapon = weapon?

naive pawn
naive pawn
#

im just asking if you have it

shy orbit
#

oh nah i dont

naive pawn
#

have you set Weapon in the inspector, then?

inland cobalt
wintry quarry
# shy orbit i dont no

you sure you don't have it in Awake or Start or something?
like weapon = GetComponent<Weapon>() for example

naive pawn
# shy orbit i dont no

wait this is meant to be "i don't, no" right? i misread it as "i don't know" lmao, sorry

shy orbit
#

here ill send my entire code one sec

#
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float playerSpeed;
    public Rigidbody2D rb;
    public Weapon weapon;

    private Vector2 moveDirection;
    private Vector2 mousePosition;
    [SerializeField] private Camera sceneCamera;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    

    // Update is called once per frame
    void Update()
    {
       ProcessInput(); 
    }

    void FixedUpdate()
    {
        Move();
    }

    void ProcessInput()
    {
        //Moving
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");
        moveDirection = new Vector2(moveX, moveY).normalized;
        //Aiming
        mousePosition = sceneCamera.ScreenToWorldPoint(Input.mousePosition);
        //Shooting
        if (Input.GetMouseButtonDown(0))
        {
            weapon.Fire();
        }


    }

    void Move()
    {
        rb.linearVelocity = new Vector2(moveDirection.x * playerSpeed, moveDirection.y * playerSpeed);
        Vector2 aimDirection = mousePosition - rb.position;
        float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg - 90f;
        rb.rotation = aimAngle;
        
    }
}
#

and ```
using UnityEngine;

public class Weapon : MonoBehaviour
{
public GameObject Bullet;
public Transform firePoint;

public void Fire()
{
    Instantiate (Bullet, firePoint.position, firePoint.rotation);
}

}

naive pawn
shy orbit
#

AH

#

found it

#

thank you

wintry quarry
#

No that's not it, unless you found something else

shy orbit
#

weapon wasnt set in the Player inspector

wintry quarry
#

Exactly

shy orbit
#

thank you guys

#

works now 🙂

naive pawn
#

@inland cobalt so your character is rolling in first person, the camera is also rolling, the gun is also rolling, but you want the gun to not roll?

inland cobalt
naive pawn
#

would rolling the gun along the axis it's pointing be viable? (as opposed to rolling the gun along the player forward axis)

#

i think that would be (more easily) achievable

celest shadow
#

hey, I've made a bunch of game objects, is there a way in the inspector to count how many of these have spawned?

naive pawn
#

select them all the hierarchy and see how many you've selected?

celest shadow
#

is there a number for that anywhere? I dont see it

naive pawn
#

it might show a number if you try to drag them?

#

im not sure unity has that

celest shadow
#

there is!

naive pawn
#

ah, nice

celest shadow
#

almost 900 and I'm starting to lag

inland cobalt
naive pawn
#

your current player/camera rolling is around the player's forward axis, right?

inland cobalt
#

its the player rolling, with the camera attached to them

naive pawn
#

but the gun is misaligned from that axis, right, since it's not pointing straight ahead, but towards the center of the screen

naive pawn
#

so would the rolling be done around the gun axis or the player axis? i think the former would be easier

fleet venture
#

Can i have like a global gameobject but still have public fields that have some references to a few different scenes?

#

it can just keep them like null when the object dont exist if the scene isnt loaded?

inland cobalt
wintry quarry
polar acorn
naive pawn
fleet venture
#

how do i work around it

#

ill give a bit more context

inland cobalt
#

so that it remains rolling with the player

fleet venture
#

i have an ApiManager script/class that talks to my backend.
this will have methods like login and register which happen in the login scene.
i have that working.
This generates a token that i want to share between all scenes but it can remain privately inside the ApiManager (like i want it to be private in there preferably).

Then when you have logged in the scene should switch and you will be able to call some other Api methods, which take different input fields in the second scene. but the token of the first will be needed there

#

i hope thats a sort of good explanation of the issue

#

rn i just have it working in a single scene

celest shadow
#

why is the editor killing me?

celest shadow
fleet venture
#

i also found stuff on that

crystal bridge
#

Hello, very new to coding and here. I have an object that I want to increase in size to be view by the player (common troupe down by simply clicking on the object with mouse button). The code I have here accomplishes that.

My problem is that the image is rotated when small (deliberate). I want the mouse click to simultaneously rotate the image to a normal view and center the image on screen when it expands.

celest shadow
fleet venture
#

ok ill try to figure that out ig

wintry quarry
#

If you want to do both things when clicking it, jsut put all of that code inside the one method

crystal bridge
#

Originally I did that, but while it doesn't give errors, it doesn't rotate.

wintry quarry
#

it rotates

#

just by a very small amount

#

OnMouseDown only runs exactly at the moment you click the mouse

#

you're doing ONE FRAME worth of rotation

#

if you want to do something over the course of many frames, you'll need to do it bit by bit in Update

#

or use a coroutine

eternal needle
# fleet venture what about ScriptableObject

you wouldnt really be using the SO for its purpose here. its more of a immutable data container for you to populate. it doesnt actually save the data if you're changing it in a build
An object in DDOL could be fine, but do you need this to be a unity object? You could just go ahead with the singleton and use a plain c# class

crystal bridge
wintry quarry
#

why are you using transform.Rotate and multiplying by deltaTime?

#

That would be something you do each frame to get a constatnt rotation over time

#

transform.rotation = whateverNewRotationYouWant;

crystal bridge
#

Tutorial that I tried to adjust 😶

red igloo
#

Im making a 3D platform game, this is my script how can I make it so when you press D the player will move forward A move backward W move away from the camera and S move close to the camera.

https://paste.ofcode.org/uRPTRiMeFkbMAQZ9AAqQ9D

wintry quarry
#

if you want to do it based on the camera, you would do something similar, but with the Camera's Transform

#

but you might also want to project those directions on the x/z plane to make it "flat" if the camera is tilted down

fleet venture
#

Im back in a bit

eternal needle
#

well theres more differences ofc but you can still use it the same as a plain c# class

fleet venture
#

Otherwise I can’t have multiple input fields from diff scenes

eternal needle
fleet venture
crystal bridge
wintry quarry
#

no...?

#

Clearly that's not right, given the errors you're getting

#

can you explain what you want to do exactly?

eternal needle
wintry quarry
#

What's the new rotation you want to achieve here?

crystal bridge
#

While object is small, it is also crooked and a mouse click expands it for the player to view. This also means that it remains crooked, but I want the crooked object to become corrected while it is big. When player clicks on the object while big, it should return to being small and crooked.

red igloo
fleet venture
crystal bridge
#

I'd also like the object to be centered on screen while big, but return to origin when small

polar acorn
fleet venture
#

i am first going to eat tho

#

ill be back in a bit

crystal bridge
#

Well, turning counterclockwise

wintry quarry
crystal bridge
#

Side Note, this is all 2D is that wasn't mentioned

wintry quarry
#

so you just want to rotate 90 degrees CCW from the curent rotation

crystal bridge
#

Probably less, but essentially yes

wintry quarry
#

transform.Rotate(0, 0, -90);

#

or transform.rotation *= Quaternion.Euler(0, 0, -90);

crystal bridge
wintry quarry
#

there is no difference. They do the same thing

#

although Rotate rotates around its local axes, which are the same in this context

crystal bridge
#

So now each click rotates it by the specified amount which makes sense, but I want it to be locked after the first click while big and vice versa while small.

So end results would be while small, it is crooked in starting position.
While big, it is fixed upright (rotated as we just did).
No other positions/states would be allowed.

wintry quarry
#

or additive rotation then

#

you shoiuld have two set rotations

#

and switch between them

fleet venture
#
public class ApiClient : MonoBehaviour
{
    private PostLoginResponseDto _postLoginResponseDto;
    
    public TMP_InputField email;
    public TMP_InputField password;
    
    
    
    public async void Register()
    {
        var dto = new PostRegisterRequestDto { email = email.text, password = password.text };
        await PerformApiCall("[redacted]", "Post", JsonUtility.ToJson(dto));
    }
    
    public async void Login()
    {
        var dto = new PostLoginRequestDto { email = email.text, password = password.text};
        var response = await PerformApiCall("[redacted]", "Post", JsonUtility.ToJson(dto));
        _postLoginResponseDto = JsonUtility.FromJson<PostLoginResponseDto>(response);
    }
}``` this is pretty much all that i have rn
#

and the postloginresponsedto contains the token

#

that i want to share between scenese

#

with other api clients

crystal bridge
#

As for a sorta 'glitch' (but not really), I notice that clicking once on object rotates it while small, click again makes it bigger. I'm trying to have both happen in one click.

I think I get what you're syaing. Like making a default position for the small size -> mouse click -> object changes to big and in different position.

crystal bridge
eternal needle
wintry quarry
fleet venture
#

i jsut dont rly know how to do the singleton thing

fleet venture
fleet venture
#

why would i even need a singleton at that point cant ijust make it static?

eternal needle
fleet venture
#

wellit was but i need references to scene objects from multiple scenes

wintry quarry
#

make what static

polar acorn
fleet venture
#

so that means i need multiple ApiManagers

#

like one for each scene

eternal needle
#

as it was written before, use DDOL (DontDestroyOnLoad) 🪄

#

you should really just look at what a singleton is before making these assumptions

fleet venture
#

i thought that did not work with object references accros multiple scenes

fleet venture
#

so if i do use a singleton can i put referenes to objects on scene 1 AND scene 2 in it?

eager elm
fleet venture
#
public class ApiTransferData : MonoBehaviour
{
    public static readonly ApiTransferData Instance = new();

    public string Token { get; set; }
        
    private ApiTransferData() { }

    private void Awake()
    {
        DontDestroyOnLoad(this);
    }
}``` so is this just what you mean?
#

like i put only the data in it?

wintry quarry
#

The point is you can access a singleton very easily from anywhere.

fleet venture
#

like you can type stuff in it

wintry quarry
#

that's very vague

fleet venture
#

how is that vague

wintry quarry
#

are these part of a menu

fleet venture
wintry quarry
#

because i don't know if it's like a thing there's 500 of or an entry form

fleet venture
#

text mesh pro input fields

eager elm
#

have a second class that handles the input fields and then writes to the singleton

wintry quarry
#

then you can access it anywhere

wintry quarry
#

like EntryForm.Instance.DoWhatever();

fleet venture
#

oh well i dont rly need that i only need the result of the operation to be a singleton

#

but i think i got it

eternal needle
fleet venture
#

i copied it from the website

naive pawn
#

what website

fleet venture
#

i guess i mixed a few things

naive pawn
#

singletons have the same concept in unity as in normal OOP, but a different implementation

fleet venture
#

so this then

#
public class ApiTransferData : MonoBehaviour
{
    public static ApiTransferData Instance { get; private set; }
    
    public string Token { get; set; }

    private void Awake() 
    { 
        if (Instance != null && Instance != this) 
        { 
            Destroy(this); 
        } 
        else 
        { 
            Instance = this; 
        } 
    }
}```
fleet venture
#

thats literally copied form that link

wintry quarry
#

close

#

no it isn't

fleet venture
wintry quarry
#

ah that link

#

that link is doing it wrong apaprently lol

fleet venture
#

oh

#

💀

wintry quarry
#

it should be Destroy(this.gameObject);

fleet venture
#

whatabout this

naive pawn
fleet venture
#
public class ApiTransferData : MonoBehaviour
{
    public static ApiTransferData Instance { get; private set; }
    
    public string Token { get; set; }

    private void Awake()
    {
        // Destroy this object if we already have a singleton configured
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
    }
}```
naive pawn
fleet venture
#

ye i did that now

queen adder
#

Just make a generic base class for singletons

#

Inherit from it when you want to expose a singleton instance for the class

wintry quarry
#

how about we crawl before we run

fleet venture
#

i only need one though

queen adder
fleet venture
#

do i just append DontDestroyOnLoad(this); in the Awake?

#

so how do i reference the singleton?

polar acorn
#

The static variable

fleet venture
#

oh

#

ye ofc

#

i thought cuz it was Monobehaviour that wouldnt work

#

so i do need to put this on a gameobjectright?

#

what happens if i load the scene for a second time with that object

polar acorn
fleet venture
#

oh it destroys

#

okay

eternal needle
wintry quarry
#

Otherwise you'll end up piling up empties

eternal needle
#

Yea no doubt its better to destroy the GO. they probably just wrote it as a safety, or maybe im looking too deep and its just a mistake

faint osprey
#

tetherJoint.connectedAnchor = tetherAnchor.position;

im trying to assign the correct anchor position but because its a child of something its putting its local position in as the value how do i do it so its the world position instead

wintry quarry
#

so the proper answer to this would be:

Vector3 worldPosition = tetherAnchor.position;
Vector3 positionInLocalSpaceOfConnectedBody = myConnectedRigidbody.transform.InverseTransformPoint(worldPosition);
tetherJoint.connectedAnchor = positionInLocalSpaceOfConnectedBody;```
#

(this is a little verbose but I did that on purpose to explain each step thoroughly)

faint osprey
#

oh so because it is connected to the player that means its position is local to the players world pos

wintry quarry
#

if you have already assigned the connected body to the joint you can replace myConnectedRigidbody with tetherJoint.connectedBody

wintry quarry
#

not just their position

red igloo
eternal needle
crystal bridge
#

Earlier issue resolved, thanks Community Members!

My next thing is I have a DragDrop function that is working. Objects grabbed by the cursor can be moved around the screen and 1 specific object (TrashSlot) cannot be dragged, but instead allows draggable objects to lock into it (typical inventory slot mechanic).

What I want to happen is as soon as object locks into the slow, it gets destroyed. The following code is accepted, but the objects are not disappearing.

#

I have tagged the objects and the slot with "TrashSlot"

strange gate
#
public void OnDamage(float dmg){
        if(invulnerable) return;
        invulnerable = true;
        TakeDamage(dmg);
        StartCoroutine(DamageDelay());
    }
    private IEnumerator DamageDelay(){
        Debug.Log("Entering DamageDelay coroutine.");
        yield return new WaitForSeconds(1.0f);
        invulnerable = false;
        Debug.Log("Vulnerable!");
    }

It never runs the DamageDelay() for some reason, how can I fix this?

rich adder
vital nexus
#

was wondering if anyone could share there thoughts on why the item doesnt respawn

eternal needle
#

also !code

eternal falconBOT
rich adder
umbral bough
#

Hi, I am making a music visualizer app in Unity and I'd like to launch it on startup.
I can't figure out how to access the windows registry because including Win32 is apparently not enough in unity.
What am I supposed to do?

rich ice
umbral bough
rich adder
strange gate
#

😅

rich adder
red igloo
vital nexus
umbral bough
eternal needle
rich adder
strange gate
rich adder
#

doesn't seem so

umbral bough
#

wym add the dll?

rich adder
#

unity doesn't include those assemblies because they are not crossplatform

#

you have to add any DLLs you want to get access to

umbral bough
#

ah, is there a way to include it only if it's a windows build?

#

I am building for both linux and windows so idk what to do tbh

rich adder
#

sure

#

in the plugin there is a platform tickbox

umbral bough
#

so do I just get the dll online or unity pm or what?
never added dlls before

rich adder
rich adder
umbral bough
strange gate
#

Thank you for the help!

cold mist
#

hey i need help with something simple

#

so i got some animation parameters that is Set to true in the script

#

but they only work whenever they're in the Loop state

#

is there any way i can go around this?

#

i feel like its easy but i can't find it

naive pawn
cold mist
#

👍

swift crag
#

Are you talking about the animation clips that get played when you set these parameters?

naive pawn
swift crag
#

ah, woops

#

I am good at reading

#

💥

umbral bough
eternal needle
serene valley
naive pawn
#

!code

eternal falconBOT
rich adder
#

i found this though . Doesn't use win32

#
string startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
        if (Directory.GetCurrentDirectory() != startupFolder)
        {
            string path = Path.Combine(startupFolder, "MyFile.exe");
            string ownPath = Assembly.GetExecutingAssembly().Location;
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.Copy(ownPath, path);
        }
umbral bough
#

will give it a try, thanks for doing the digging for me

loud vault
#

Something about my game's resolution is off. In windowed mode the game looks good, but in full screen the edges are jagged
Another thing is that to take a pic of the jagged graphics I had to take a pic with my phone, because if I take a screenshot it looks like in the windowed version
Maybe it has something to do with the monitor resolution settings?

rose canopy
#

i think my unity might be bugged?
On one project im able to multiply float by Vector3
float deez = deez * transform.right;

But on another project this gives me an error saying that you cannot convert vector3 to float. Am i missing something????

rich adder
#

imagine Vector(1,1,1)
and float is 3

3 x 1 , 3 x 1 , 3 x 1
= Vector3(3,3,3)

naive pawn
rose canopy
loud vault
rich adder
#

this is literally not a float

naive pawn
crystal bridge
loud vault
#

I'll try in unity talk

west radish
eternal needle
west radish
#

even this shouldn't work float deez = 1f * transform.right

rose canopy
#

i figured out why i didnt get an error when i wrote that maybe? i didnt have the actual unity project open i just had the script cause i wanted to test if i would get an error writing it in a different project?

grim eagle
#

why is "playerscore + 1" red? (this is VERY basic mb 😭) (i'm following a pre unity 6.0 tutorial)

polar acorn
#

You're just adding one and doing nothing with it

polar acorn
polar acorn
umbral bough
grim eagle
#

thanks!

#

do i need to add "class"?

wintry quarry
#

Are you trying to follow a tutorial or something

grim eagle
#

ooh, could be

grim eagle
wintry quarry
#

If you're following a tutorial, you missed a step

#

or

#

yes

#

you named it something else

#

I recommend if you're following a tutorial to do it verbatim

#

Tutorials are for learning

#

they're not for creating an end product. You watch the tutorial to learn how it works, then apply those learnings to create your own thing.

grim eagle
#

yep

polar acorn
grim eagle
#

it doesn't work notlikethis

#

found it lesgo

rich adder
umbral bough
rich adder
umbral bough
#

odd

humble marsh
#

Hello! how do you get a rotated transform localpoint to world position? transform.transformPoint() doesnt seem to work, as the selected cube is where it is in local spaces, but where the wood is, is where it goes to when made into world space.

swift crag
#

Perhaps you meant to use its parent transform

#

TransformPoint takes you from the local space of a Transform to world space

#

The position you see in the inspector is your local position, whose world-space meaning depends on the parent transform

humble marsh
#

yes, i want to make it into COMPLETELY world space. ie no parent

#

but when i use the function to transform it into world space it teleports the point to another location

swift crag
#

where is this local position coming from?

humble marsh
#

logcutting1 has a attached collider, the collider min and max is in local space compared to the logcutter

#

i use logcuttor to transform it into world space

swift crag
#

there is no "logcutting1" or "logcuttor" object in this screenshot

humble marsh
#

I mean to say Logcutting(Clone) mb

swift crag
#

okay, so you have a box collider attached to "Logcutting(Clone)"

#

show your code

humble marsh
#

yes, i have it attached, and i get the min / max by using center +- size/2

#

im trying to transform all points into world space, to use for calculations.

rose canopy
#

I have a top down game, im procedurally tilting the character model based on input. but when i rotate the character model to say look left, and then i start moving, it tilts based on its rotation so clicking W which moves you up it would Yaw left instead of pitching down, how do i make it tilt based on world XYZ or even based on the Character Controller rotation which doesnt rotate?

swift crag
#

you're using transform, so you're getting the Transform of that object

#

perhaps you meant to use collider.transform

humble marsh
#

the Birch_1 object, and yes i know, i tried that when collider.transform.transformpoint didnt work. as you can see in the comment

swift crag
#

well, collider.transform.TransformPoint is the correct thing to do

#

it will transform a point from the local space of the collider's Transform to world space

#

and you've calculated a point in the local space of the collider's Transform

humble marsh
#

yeah, which is pretty wierd, since in local space, the collider min/max are on the collider, but when transformed into world space they just, arent

swift crag
#

use Debug.DrawLine to draw a line from the origin to the calculated world positions

#

give it a long lifetime so it doesn't instantly vanish

wintry quarry
swift crag
#

that would make things more confusing, yes

humble marsh
#

so, wierd problem. uh, drawline fixes the position.

#

but yes, the handle is pivot

wintry quarry
#

ok

humble marsh
#

I'm going to have to debug more, the issue is sometimes fixed. sorry to waste your guys time, and thank you.

honest haven
rocky canyon
#

it can take some time b4 unity registers the disconnection

#

the new input system wil update instantly i think..

#

you could poll Input.GetJoystickNames(); every second or so..

sour fulcrum
#

All definitions of ScriptableObject and MonoBehaviour classes have to be in their own .cs file with 1:1 matching names for serialization purposes right?

swift crag
#

Names don't have to match in newer versions of Unity

#

but yes, you may only declare one such class per file

#

Unity only cares about the GUID of the ScriptAsset.

sour fulcrum
#

ah pain, ty

#

have a handful of classes i gotta define explicit generics for and it would be a lot cleaner to just knock them all out in 1 file aha

#

eg.


[CreateAssetMenu(fileName = "EnemyManifest", menuName = "GAME/ScriptableManifests/EnemyManifest", order = 1)]
public class EnemyManifest : ContentManifest<ScriptableEnemy> { }

[CreateAssetMenu(fileName = "ItemManifest", menuName = "GAME/ScriptableManifests/ItemManifest", order = 1)]
public class ItemManifest : ContentManifest<ScriptableItem> { }

[CreateAssetMenu(fileName = "InteriorManifest", menuName = "GAME/ScriptableManifests/InteriorManifest", order = 1)]
public class InteriorManifest : ContentManifest<ScriptableInterior> { }

#

oh well

swift crag
#

cool trick: you can use consts in attribute parameters

#

so you could write Menus.ManifestPrefix + "EnemyManifest"

#

as long as ManifestPrefix is a const string

sour fulcrum
#

oh fair, i could probably through in a nameof there too right

swift crag
#

that too

sour fulcrum
#

heard chef

ruby zephyr
#

Do you guys have any transcript, or a lesson for unity together with c# for reading?

#

Because I think I learn better with reading

#

Something that is up to date or if not, is still helpful

slender nymph
#

after that, it's really just a matter of understanding some of the fundamentals of the engine which you can learn from the unity !learn site which typically have text along with the videos

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

swift crag
#

The documentation is also worth reading.

#

I wouldn't just read the scripting documentation from start to end -- you want to look in the manual

#

It covers higher-level ideas, like game objects and components

scenic saffron
#

How do I get the vectors perpendicular to the transforma.forward vector?

polar acorn
swift crag
#

This is a bit tricky in general!

#

I mean, in this case, you can just use transform.up and transform.right

polar acorn
#

There are an infinite number of perpendicular vectors for a given vector in 3D space

#

So you need another one to choose which of those you want

swift crag
#

But generally: consistently finding two tangent vectors is hard. There's no general way to pick them with no context.

#

You can start with world-up and then orthonormalize (make the two tangent vectors perpendicular to both each other and the original vector) -- but then it freaks out if the vector points straight up

#

It's an interesting problem. It comes up quite a bit in shaders..

#

this is the same problem that comes up for Quaternion.LookRotation

#

if you ask for a look rotation that's straight up, you'll get weird results, because LookRotation defaults to using Vector3.up for the "up" direction

forest summit
#

ive recently been getting a lot of errors about "ambiguous references" that i never got before on my project, why is this happening cause everything seemed fine until this popped up, and i didnt even change anything

vagrant mist
#

Is there a simple way to visualize a RaycastHit2D array?

verbal dome
#

Loop + Debug.DrawLine

vagrant mist
#

So inside of an update method or make a loop?

frosty hound
#

Wherever you made the raycast, just add the Debug draw after it.

vagrant mist
#

where I made it or where I'm casting it?

frosty hound
#

Casting

vagrant mist
#

Debug.DrawRay or DrawLine?

frosty hound
#

Either will work

#

Ray will take a point and direction, and line will take a point and destination.

vagrant mist
#

so I think I want to do Ray, now the arguments themselves confuse me a bit
I'm thinking Debug.DrawRay(Vector2.zero, Vector2.down, ---);
not sure about what to do where I put the dashes

#

hol up, intellisense mightve saved me

vagrant mist
#

I dont think either of those helped

#

so I recompiled it and everything runs fine, but there are no lines being drawn

  public ContactFilter2D castFilter;
  public float groundDistance = 0.05f;
  CapsuleCollider2D touchingCol;
  RaycastHit2D[] groundHits = new RaycastHit2D[5];

 public bool IsGrounded { get
     {
         return _isGrounded;
     }
     private set {
         _isGrounded=value;
         }
 }

  private void Awake()
{
   
    touchingCol = GetComponent<CapsuleCollider2D>();

}
  void FixedUpdate()
{
  IsGrounded = touchingCol.Cast(Vector2.down, castFilter, groundHits, groundDistance ) > 0;

   Debug.DrawRay(Vector2.zero, Vector2.down, Color.yellow, 10);
}
#

this is roughly what it looks like

frosty hound
#

Do you have gizmos turned off?

#

You're also using the world origin, so are you looking in the wrong place?

vagrant mist
#

i could be, gizmos all look good

#

how would I change it to target the player?

frosty hound
#

Give it the position of the player for the first argument.

#

This script is on your player, no? Use transform.position, then.

vagrant mist
#

yeah its on there, this is actually a separate script for this specifically

#

I'm trying to see why my isOnWall and isOnCeiling bools keep going on each time my player lands on the ground because I think its the reason my player stops for a split moment and loses all speed

drifting cosmos
#

is there a default scene that loads when you launch the game like how does it know which scene to load

teal viper
sour fulcrum
#

In THEORY setting RenderSettings.skybox to a instanced version of itself made at runtime should make it safe to mess with without messing up the editor one, right? Assuming the active scene has not changed between me applying my new material and me messing with it

#

I was under the impression RenderSettings.skybox directs to the active scene's skybox, no?

#

why are my logs saying otherwise 😭

#

can you really not access the rendersettings of additive scenes even if they are actively being used?

#

oh you can use resources.findobjectsoftypeall but that seems disgusting

frigid sequoia
#

If a script has Coroutine running, what would happen first, the Update method of that script or the Coroutine?

#

It's random by default?

frigid sequoia
#

Mmmm, makes sense I guess

sour fulcrum
#

can i just not fuck with the skybox when using additive scenes without some hdrp nonsense?

#

the answers im finding online are insane

chilly magnet
#

Any beginners, DM me, I am working on a cool hobby project and I am looking for people to help me.

teal viper
sour fulcrum
#

this is true

#

but you cannot modify them

#

from what i am reading and trying

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

teal viper
chilly magnet
sour fulcrum
#

as in your not sure about that or that doesn't sound right?

teal viper
#

What setting exactly are you trying to change?

sour fulcrum
#

I've got a lobby scene and a level scene, the latter additively loads and unloads on request

I have a time of day system and wanted to manipulate the level skybox to reflect the time of day

#

I agree in that it doesn't sound right but honestly seems cooked

#

RenderSettings is exclusively static calls to c++

#

I was hoping they existed per scene and they do but there's nothing actually in each of them i can touch

frigid sequoia
#

Ok, this is kinda more of an organization thing, but I may ask anyways. When you have like something that can be either one thing or the other, do you guys use a bool or create an enumerator for it?

#

Like let's say u have physical damage and magic damage. Do you call it by bool isMagicDamage or do u specifcy it?

eternal needle
#

for damage types, id just make an enum incase i ever add more later. it also just makes more sense logically like it can be physical or magic. its not really a case of "is it magic or not"

sour fulcrum
#

Not to overengineer but scriptableobject might also be nice for damage type for other related data, even just visual stuff like icons

frigid sequoia
#

Also, probably slightly worse on performance??? Not sure

eternal needle
#

the inconvenience lasts 5 seconds and just makes more logical sense. logical code is good

eternal falconBOT
eternal needle
frigid sequoia
wary sable
#

Hello,

I am making a basic movement controller for a cube, and want to give it a jump function that allows it to keep its horizontal momentum after jumping. I have tried a few ways like directly changing the velocity but that doesn't seem to do it. My next assumption would be to somehow create a vector based off of the x and z velocities and multiply that with vector3.up in an Add force, but I'm a little lost. A hard shove in the right direction would be apprecitated!

https://paste.mod.gg/rypxibbqbgjp/0

frigid sequoia
#

Not much, but not sure if I would go through the slight hassle of making it an enum for readability when I am the only one that is gonna read it anyways if it's also gonna be worse in the end

eternal needle
frigid sequoia
#

I do know, but stuff like this are gonna happen like constantly on the game, so why make it more complex for no reason, even if only slightly?

eternal needle
frigid sequoia
#

I don't think it's really that much easier to read, or is it?

sour fulcrum
#

not to nitpick but incoming with 1 m and not 2

wary sable
#

thanks

eternal needle
sour fulcrum
#

Unity probably does one thing stupidly somewhere that costs more than hundreds of those kinda micro optimisations

eternal needle
#

i dont really understand why you wanted to ask on enum vs bool if you were gonna choose a bool for "performance" anyways