#💻┃code-beginner
1 messages · Page 612 of 1
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
its fine if all ur doing is reversing direction
mine is 3D and reflect in the direction you aim at
alright
i wanna do something stupid; i wanna control where it is in the scene the players spawn
pretty vague
use an empty gameobject
"SpawnPosition"
instantiate(prefab, SpawnPosition.position, Quaternion....)
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
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);
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
Thank you
just want it to be optimized :)
ty too didnt even notice
i was locked in for a sec lmao
when TMP is not an option, can also use StringBuilder iirc much better than new string
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
yea just meant in general
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
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

pro-gamer move
yield return oneSecondWait
Exactly; the only way to do it . . .
nested while loops is the way XD
I hardly find myself using any Yield Instruction anymore
quesiton; how can I arrange it so
DontDestroyOnLoad();
refers to itself
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?
what do you mean by "refers to itself"?
the gameobject holding the script itself won't be destroyed on load
DontDestroyOnLoad(this) or DontDestroyOnLoad(gameObject)
gameObject
roger roger
basically
gameObject is the entire object
this is the script/component
in DDOL that means the whole object anyway
Can you also help with backups? How do you create backups?
either use Version Control, or duplicate and zip for local backups
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.
no
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
"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
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?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
what youtuber ? why are you listening to youtubers
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.
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
Tutorials and tips Like
- Be motivated
- Don't Copy Codes
- Copy it your own way
- Make small games
- Participate Game Jams
And more
sure. more or less.
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
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?
aside from Unity Learn most of the Unity C# tutorials are complete dumpster fires
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
what exactly do you mean with "Unity programming"
no. Im talking about the normal C# learning
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
Do I do hands on learning?
Oh okayy sorry, btw we had a long conversation already soo.. To summarize, What should I do?
do a bit of both
learning regular c# on its own, apply those concepts in unity then slowly start using unity specific methods / components
https://learn.unity.com/project/beginner-gameplay-scripting
this is good too it hammers the point of C# in unity context
Alright thats nicee, thanks very muchhh 🤗
https://paste.ofcode.org/bQLwbfjMzMy3UamuUYG38p does anybody know why my code doesnt detect the center of the screen i have a tag named center but it doesnt seem to detect from this script
Try putting a log before the if and log the tag of the object you hit
ok i will try that rq
Is there a "best" way to start? or at least a preferred route?
previous convo starts here
#💻┃code-beginner message
mostly where the links are
in a nutshel Unity learn site and Microsoft's website
so i put the name of the gameobject it hit and it shows enemies but never the target gameobject
I see well thank you 
The Three Commandments of OnCollisionEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt be moving via a 2D Rigidbody on at least one of them
where and what did you even log?
show new code
dynamic 2d rigidbody
yep i made sure to do that
If it's not dynamic you couldn't be moving via rigidbody
kinematic can still call OnCollision if the other object has dynmaic rb
Right, hence the "At least one of them"
oh was replying to original Chris message they edited
yeah, at least one has to be a dynamic rb
so on the object that is moving i should have a dynamic rigid body?
You need to be moving it with a dynamic rigidbody. If you're moving it by changing it's transform position it won't work
i mean, MovePosition exists.
You have to actually be using the rigibody to handle the movement
weird..fun fact Physics2D kinematic has velocity 🤔
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
huh
thats why they have the "Static" flag
does that mean i cant move my character like this https://paste.ofcode.org/sDXqh9eVQXi8t46uSyyrsq
not at all
this is essentially teleporting
the dynamic rigidbody has to play "Catch up" every physics tic.. not good
Correct. You'd need to actually move with the rigidbody
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
any tips for applying seek using rigid body
applying seek?
seek steering behavior
most of the time you can just replace it 1-1
transform.position += (Vector3)(velocity * Time.deltaTime);
with
rigidbody.velocity += velocity
intresting thank you
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
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
huh?
i havent used the bot before do i just put the code in there and post here?
use one of the links, paste the code, hit save. Send the generated link
ty
Use Scriptbin to share your code with others quickly and easily.
btw this will create TONS of ragdolls (creating one each frame)
if health is 0 or less
what are you trying to Reset the positions/rotations of ragdoll you mean?
nah it doesnt ik its not the best optimized
basically just want them to get back up where the ragdoll finishes
doesnt enabling Animator already do that?
nah for some reason they spawn on the parent
or where the ragdoll started instead of ended
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");
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.
breakpoints in debugger?
the rest of the parameters are out params, so wouldn't the kernel ID be the only relevant one?
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?
I can print out that one by just debug.logging the find kernel function and its ID is zero.
invalid kernel index seems pretty clear
doesnt FindKerner return a string?
hows a string get in an index wanted in GetKernelThreadGroupSizes
no it returns a kernel index
It returns an int
ahh yea myb my eyes are broken
Can you show your shader?
A tool for sharing your source code with the world!
make it mp4
It returns a zero which is less than 3 and not negative so it shouldn't be the index's fault... I think...
it's weird to me it's returning 0 if CSMain is not the first one defined. But maybe it uses the pragma order?
I mixed around the pragma order and yeah it shows 1 in the console now.
and still has the same error?
Yes
but with 1 this time?
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
Hmm ok, good to know. Thanks 
ty ill look at this
I think if you look at the shader inspector you may see the compile error
looks like itll fit perfectly
yeah tbh what You got seems a bit more code than it normally is lol
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
I can't believe I didn't think to look in the compute shader itself for compiler errors...
I may be stupid.
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
not sure its related but you should never multiply mouse by Time.deltaTime
That's causing it, yes
delta already returns the distance between frames
If a frame takes longer to render, you'll get more mouse movement
ah i get what you mean, cheers
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
i get what you mean now, I overlooked the fact that delta is already framerate independent, thanks
yeah that's a whole lot smoother
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
Vector3 myInitialPos
...
myInitialPos = transform.position
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
working on it
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
int count = FindObjectsByType<T>(FindObjectsSortMode.None).Length;
okay, sorry, ive just been using it to automatically assign references
I think it searches all scenes open too so keep that in mind
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
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
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
just make a curved sprite
duplicates of what? wdym?
And it just generates the curved sprite instead of the square?
instead of the square?
wdym leave the player object open?
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
Well yeah rn every time you eat the food it places a square sprite behind the head, are you just saying to just use a circle instead
and it can keep going for as long as it takes
make 2 sides a circle and 2 sides a square
whats the need to spawn a new player each time?
modularity...
how?
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
So like a half oval
like see the bottom left quad
I’ll try it out tomorrow and get back to you
is making an object thats of a type of one of its inherited things for generics only or is there other reasons
Can you be more specific about what you mean?
like you make an object of class Class_ and it inherits from interface interfac and then you make an object of Class - but with the type of interfac
the persistent level disappears as soon as I move to another level
I thought the point was it persists!
why does it go away?!
dont destroy on load?
an object in that scene is set to that
Classes cannot inherit from interfaces, they can only implement interfaces.
As for assigning a value of a type to a variable of a broader type, that has nothing to do with generics
Wdym by persistent level
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
like whats the reason for making a class object of an interface it inherits is it only so you can have a class thats uses that interface like the generics <interface>
You need to call DontDestroyOnLoad on the GameObject, not the script instance
no- right
You kinda have it backwards. You write code that can deal with the interface, and then you are able to reuse that code for any object that implements the interface
it is there once I start the game, and GONE the moment I change the level
So you only need to write it once
Only GameObjects in the DontDestroyOnLoad special scene will survive a non additive scene load
it is set to additive though
Some other code is unloading the scenes then
Or calling LoadScene without Additive
i kind of need it to be additive though
its got the canvas needed for fade to black and ui elements
I didn't say not to make it additive
thats exactly what you said
Never said that
calling Load Scene without Additive -> remove additive -> don't make it additive
It was an extension of the thought above it:
Some other code is unloading the scenes then
Or calling LoadScene without Additive
from a beginner standpoint interfaces can be kinda hard to learn because a lot of their primary usecases exist in spaces outside of Unity where-as in Unity making a separate monobehaviour component usually fills those demands
im trying to figure out whats the point of making an object of like this interface class = new class
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);
}```
There's very little point to doing precisely that and it's quite rare
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
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
... right
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.
is there a way to store the last position of my player in another scene?
Vector3 lastPlayerPosition;
scenes themselves don't store anything
you can store data on scripts that you put instances of in scenes
and that relies on the object holding the script to be constantly present, right
through instance
If you want the data to stick around, the object holding the data has to stick around
instance as you put it is just a convenient accessor variable.
The thing you're thinking of is DontDestroyOnLoad
Well if you look up any Unity singleton implementation, it includes code for handling such copies.
thats not how you create instances?
Everything in the scene is an instance
every actually instantiated object is an instance
right- instances carried over to another scene
that means "don't destroy on load" doesn't it?
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.
right right right
so I have the variable created and it tracks where the player is
how, then, do I use it
Presumably we're talking about some script that holds the player position data?
the script holding the variable gets destroyed when I load another level
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```
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
same error and when same thing happens
Try commenting out sections to see if what's causing the crash is within this function
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?
How do you mean?
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.
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
Can singletons persist through scenes?
if the object isn't destroyed
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
If this is for github then if the file is above 100 mb you need to add it to lfs
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?
If they are set to DontDestroyOnLoad, then yeah they will persist across scene loads
I'm pretty sure your right in that the screenshot is wrong but prefabs exist in runtime in hideanddontsave no?
i guess not explicitly as prefabs but
pretty sure thats not intended for any actual game data, let alone data between scenes at the runtime
thats just for settings and such
The runtime instance has no connection to the prefab instance, so the entire logic of making a prefab to fix a bug to do with the runtime instance is fraught
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
In which loop are you doing this?
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
@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...
i mean update loop, fixedupdate loop? otherwise your lerp doesnt make sense
Ah the method is being called from Update
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)
door is null not the rotation
only thing that can be null on that line is door
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
@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
There are more than one way to do this
u can either do it 3D 2D or do 3D then bake it into 2D etc etc
I wanna do how Township did it. So what should I do
do you wana do exatly how they did it?
Yes. Or atleast want to know how did they do it exactly
Why are you dividing by delta time?
@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
I'm pretty sure you should be multiplying by delta time not dividing by it if anything.
Also I don't think mouse input should be modified by delta time since it is already frame rate independent.
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
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
You should remove it from the line where you are multiplying mouse by it
Also I would just use Quaternion.RotateTowards or Vector3.RotateTowards
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 🥲
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
Are you reffering to this line ?
door.localEulerAngles = new Vector3(0, rotation, 0);
Let me know if you don't understand
@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
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
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
Dont really know what you mean here but stop applying Time.deltaTime as a factor to your mouse movement. It simply is just not correct
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!
Also if you want to do smoothing in a more correct way look into Mathf.SmoothDamp
this is where I got my old solution from
https://stackoverflow.com/questions/55963533/unity3d-input-getaxis-for-mouse-not-consistent
with solved my issue with the inconsistency
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?
Yeah I tried it and it works now, thanks
youre welcome :)
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;
}
}
Is there a 2d equivalent of Gizmos.Draw or is using DrawGizmos fine
a quick google doesn't bring anything up
https://github.com/miguel12345/UnityShapes I've use this, not the best thing but it works
https://openupm.com/packages/com.zchfvy.gizmosplus/ this one also seems interesting, but it's not something ive tried
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
I just want to draw a physics2D.boxcast to help visualize boundaries
what do you think works best?
just make a cube with the right size to show the rectangle boundary,
Thanks!
when viewed side on, a cube is exactly the same as a square
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
This looks really great
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™️
I forgot about this one!
Wow you wrote this!

nah, Vertx (one of the mods) did, i just had one PR lol
I will check this out!
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.
It's fine to repost your questions after a while if the original message got buried.
You don't always get a direct answer. Bump your message so people can look at it.
Did you check if Anikki was right with their response?
yes but it does not give me any idea on how to make the plane turn to where the free cam is facing
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
bet
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?
you could turn off automatic recompilation and manually press ctrl+r to recompile/reload assets
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
I've got a pretty recent cpu and plenty of ram, i dont think its that. Also my project is starting to grow but its no where near what real game devs would consider to be a "big project", like I've got 4 materals, 2 dozen scripts and all my graphics are default cubes and capsules
it shouldn't take more than a few seconds then
is there any feature specifically that takes a lot of work in this process? is it the few shadergraphs I've built?
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?
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
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
you probably havent set a bullet prefab object in the script
check the component on its game object and see if theres a blank space there for your prefab
then you need to check the stack trace because something deeper down is null. your error doesnt tell much
it's mostly related to scripts and serialization/deserialization
if you're on Windows, maybe your project is being synced with OneDrive constantly? or maybe Windows Defender is doing something weird with it?
I think you're able to open the profiler and inspect what's causing the long loading times, but looks like it's something external
you can't modify that rect, you have to replace it
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();
}
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
id recommend a breakpoint and inspecting the values of these at runtime. if everything is set correctly at runtime then you shouldnt get a null ref
how do i do that?
where's ProcessInput?
the if statement is inside ProcessInput
uhhh are you using visual studio?
yeah vsc
that still gives me an error on progressBar.rect = rect cause it says its read only
and line 37 is pointing to Weapon.Fire, right?
yeah
vsc is not visual studio, which one are you using
ok, so it's Weapon that's null
im using vsc
check your PlayerController, have you assigned Weapon correctly?
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
its assigned as public Weapon Weapon;
(also btw, the variable should probably be weapon instead, so you can differentiate between the class and the variable
that's a declaration; you'll have to assign it somewhere in your script or within the editor
it will look like this
do you have any Weapon = ... in your script?
i dont no
shit, mb, nvm
im now noticing that you're calling this a progressBar, why not use a slider for that?
anyone
read your script. do you have any Weapon = ... in PlayerController
in my game my character is able to rotate in the y axis (roll)
the y axis isn't roll
you don't need it
im just asking if you have it
oh nah i dont
have you set Weapon in the inspector, then?
sorry i forget its the other way around in unity, regardless, i meant roll
you sure you don't have it in Awake or Start or something?
like weapon = GetComponent<Weapon>() for example
wait this is meant to be "i don't, no" right? i misread it as "i don't know" lmao, sorry
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);
}
}
@shy orbit
No that's not it, unless you found something else
weapon wasnt set in the Player inspector
Exactly
@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?
i want the gun to roll with my camera, but the issue is the script above that attempts to make the gun aim at the crosshair, which counteracts that rotation when looking at the raycast hit point, the weapon is a child of my camera offset
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
hey, I've made a bunch of game objects, is there a way in the inspector to count how many of these have spawned?
select them all the hierarchy and see how many you've selected?
is there a number for that anywhere? I dont see it
ah, nice
almost 900 and I'm starting to lag
sorry mind clarifying what you mean? Im not sure i follow
your current player/camera rolling is around the player's forward axis, right?
yes
its the player rolling, with the camera attached to them
but the gun is misaligned from that axis, right, since it's not pointing straight ahead, but towards the center of the screen
yes
so would the rolling be done around the gun axis or the player axis? i think the former would be easier
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?
But im rotating the gun with LookAt(), im not rolling relative to anythings axis surely, just pointing at a position in space
you cannot reference objects in other scenes except at runtime when both scenes are loaded.
You cannot reference scenes themselves.
A singleton, but when you're writing the code for the instance to self-terminate, first have it beam its references to the existent singleton
right now you have that, i mean what do you want
oh
how do i work around it
ill give a bit more context
i want it to do what its already doing, without affecting the roll axis at all
so that it remains rolling with the player
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
why is the editor killing me?
you could mark the object as DontDestroyOnLoad and it will hang around between scenes. Just be careful if you load a scene that has the object in it, you could hit some conflicts. Best to instantiate it programmatically and use a singleton pattern to make sure it only happens once
what about ScriptableObject
i also found stuff on that
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.
I dont know much about scriptable objects sorry
ok ill try to figure that out ig
You can't have two methods with the same signature like that
If you want to do both things when clicking it, jsut put all of that code inside the one method
Originally I did that, but while it doesn't give errors, it doesn't rotate.
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
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
Yeah, I want only one frame (no animation). I increases the rotation speed to higher values (50f) to see if there was a noticeable increase, but no change.
just set the rotation to the desired rotation then
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;
Tutorial that I tried to adjust 😶
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.
Uh ye maybe idk
Looks like you're currently trying to transform the input based on the direction the object the script is attached to (the player?) is facing:
Vector3 MoveVector = transform.TransformDirection(PlayerMovementInput) * speed;```
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
Im back in a bit
the only difference if its a monobehaviour is you'll need to use DDOL for your singleton too
well theres more differences ofc but you can still use it the same as a plain c# class
But ideally I would have a diff api script so it can have diff input fields in each scene so then I only need to share some variables and not keep the entire object
Otherwise I can’t have multiple input fields from diff scenes
this is really vague and honestly got no clue what this has to do in relation to your initial problem of a token that you can share between scenes
Like I login on scene one and I get a token that I need to pass to scene two to do more api stuff with
Like this?
no...?
Clearly that's not right, given the errors you're getting
can you explain what you want to do exactly?
yes that is the initial problem of "a token that you can share between scenes". The whole rest of the message was vague. It'd be a lot easier to understand if you could share the code that you're struggling with
What's the new rotation you want to achieve here?
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.
Like this?
Vector3 right = cameraTransform.right;
Vector3 forward = Vector3.Cross(right, Vector3.up).normalized;
that's really vague
i dont have a github repo cuz i didnt know how to do that with unity
I'd also like the object to be centered on screen while big, but return to origin when small
What value do you want to set the rotation to
so what rotation do you want
Vector3.ProjectOnPlane
I was planning on adjusting the value after coding was set correctly, but the object is a square shape that should be 90 degrees.
Well, turning counterclockwise
counterclockwise around what axis
Side Note, this is all 2D is that wasn't mentioned
so you just want to rotate 90 degrees CCW from the curent rotation
Probably less, but essentially yes
transform.Rotate(0, 0, -90);
or transform.rotation *= Quaternion.Euler(0, 0, -90);
Cool, these both worked in rotating. Can you explain the difference?
there is no difference. They do the same thing
although Rotate rotates around its local axes, which are the same in this context
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.
You shouldn't be using Rotate really then
or additive rotation then
you shoiuld have two set rotations
and switch between them
ok im back what code do you need
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
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.
Not sure how I'd set that up while retaining size changes. Should the positions be a separate script?
🤷♂️ you said here something about a problem #💻┃code-beginner message
im not sure what code you have or still what the problem even meant.
as for the token, still just a singleton should be fine
empty GameObjets would be easiest
i jsut dont rly know how to do the singleton thing
should i not put it on this class then?
learn!
why would i even need a singleton at that point cant ijust make it static?
thats up to you, im not sure what the lifetime of that object is intended to be. from your initial messages it sounded like you had some ApiManager class which i assumed you would make a singleton and put the token on
wellit was but i need references to scene objects from multiple scenes
make what static
as it was written before, use DDOL (DontDestroyOnLoad) 🪄
you should really just look at what a singleton is before making these assumptions
i thought that did not work with object references accros multiple scenes
i know what the concept of a singleton is
so if i do use a singleton can i put referenes to objects on scene 1 AND scene 2 in it?
You should never put scene references in a singleton since they won't exist / will be destroyed.
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?
what exactly are these things you're referencing?
I think you kinda have it backwards. YOu don't need a singleton to hold references to stuff.
THe things you want to hold references to should just be singletons themselves
The point is you can access a singleton very easily from anywhere.
they are input fields in the scene
like you can type stuff in it
that's very vague
how is that vague
are these part of a menu
this
because i don't know if it's like a thing there's 500 of or an entry form
text mesh pro input fields
have a second class that handles the input fields and then writes to the singleton
Ok cool - wrap this up in a script and make that script a singleton
then you can access it anywhere
ye okay
like EntryForm.Instance.DoWhatever();
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
this solves it i think
you cant new a MonoBehaviour and no this isnt a singleton pattern that'd work in unity. One was linked to you above
i copied it from the website
what website
i guess i mixed a few things
singletons have the same concept in unity as in normal OOP, but a different implementation
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;
}
}
}```
not quire
thats literally copied form that link
it should be Destroy(this.gameObject);
whatabout this
what website is this
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;
}
}```
its this one
use this @fleet venture
ye i did that now
Just make a generic base class for singletons
Inherit from it when you want to expose a singleton instance for the class
how about we crawl before we run
i only need one though
Good point I'll just let you guys chill
do i just append DontDestroyOnLoad(this); in the Awake?
so how do i reference the singleton?
The static variable
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
What does your code say it does when there's already an instance
maybe it assumes the object could have other components on it
Indeed but that's an unusual approach and you would also need some kind of manager keeping track of all the GameObjects then as well
Otherwise you'll end up piling up empties
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
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
the connected anchor position will be in the local space of the connected Rigidbody
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)
oh so because it is connected to the player that means its position is local to the players world pos
if you have already assigned the connected body to the joint you can replace myConnectedRigidbody with tetherJoint.connectedBody
The connected anchor position is relative to the player's local coordinate system
not just their position
also how do I stop the player from climbing the box like that very annoying.
which part of it are you trying to solve, that its pushing a box or that it's moving on such a steep angle? for the angle you'll have to cast down, likely using a capsule cast, and then check the normal of what you're standing on to see if you should be able to move or not
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"
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?
do you want the box to rotate like that at all ? You could also just lock box rb X/Z rotation ?
was wondering if anyone could share there thoughts on why the item doesnt respawn
have you debugged if the OnTriggerEnter2D function is being called? you have debugs in the other methods
also !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
check
Gameobject with the coroutine should not be Disabled.
Timescale must not be 0
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?
seems like you never call "DestroyItemAndRespawn"
Googling was useless btw because p much all the forums just tell you to use player prefs because nobody wants to answer the question but they do wanna play smart.
Sorry, what do you mean by that? Im pretty new to Unity so I dont understand these terms so much yet
😅
hmm..first did you verify that OnDamage gets to start coroutine line at all? I don't see a log in that method
if you watch the video when I am pushing the object the player climbs up which I dont want
this is within my player script, that destroys it
as I said, I don't have access to RegistryKey
I need it to still rotate
yes i saw, the rest of my answer above addresses that
it will still rotate just not angled
I had a few extra logs before this, the OnDamage() gets executed, but it doesnt execute coroutine
did you add the dll properly?
doesn't seem so
wym add the dll?
unity doesn't include those assemblies because they are not crossplatform
you have to add any DLLs you want to get access to
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
so do I just get the dll online or unity pm or what?
never added dlls before
gotta find the path for linux. Thats tricky I suppose because so many different distros
You just put it inside your Assets/Plugins
it's fine, linux users are usually capable of handling the startup themselves, making it launch on startup on windows is the priority, will take care of linux afterwards
Just fixed the problem, i started to test each line and turns out it was TakeDamage that was the problem
Thank you for the help!
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
👍
Any ideas?
Parameters don't have a "loop state"
Are you talking about the animation clips that get played when you set these parameters?
(been moved)
yes
I am actually disabled when it comes to this, where can I find the dll I need?
I couldn't find anything official and I don't wanna just get random stuff.
#💻┃code-beginner message
i replied to you above
can anyone help me whit how i can make in this script so that a reload animation happends when i begin realoading bc idk anything about coding
https://paste.mod.gg/iemwkjrgmpxt/0
A tool for sharing your source code with the world!
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
normally its already there in the .net framework folders unity downloaded, its jutst omitted or you can download nuget packages and extract them like a zip to take the DLL from lib folder with correct .net version.
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);
}
will give it a try, thanks for doing the digging for me
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?
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????
this is a code channel
deez * transform.right returns a vector3 not float
imagine Vector(1,1,1)
and float is 3
3 x 1 , 3 x 1 , 3 x 1
= Vector3(3,3,3)
On one project im able to multiply float by Vector3
But on another project this gives me an error saying that you cannot convert vector3 to float
these are not contradictory, these are simply different things (that are both true)
this same line of code in 2 different projects one returns an error
Where am I supposed to ask? Under the art channels?
what?
this is literally not a float
perhaps #🖼️┃2d-tools or just #💻┃unity-talk, but i think that's just a moire effect?
Sorry, I had missed this, but upon reevalutaing I shortened the code and more importantly forgot to add rigidbody to one of the objects (I had thought I did this).
The moire effect is because I can't show the low resolution without taking a picture with the phone, because any screen capture shows the correct resolution, but not the gameplay
I'll try in unity talk
there is no way that you could have written float deez = deez * transform.right; that line in itself it not valid C#
i dont think you need a rigidbody, id possibly not even use OnTriggerEnter2D here actually. If you drag it over the trash without letting go, wouldnt it delete the object in that case?
Maybe when the drag is finished, do like an overlap circle to get all the colliders around the area
even this shouldn't work float deez = 1f * transform.right
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?
why is "playerscore + 1" red? (this is VERY basic mb 😭) (i'm following a pre unity 6.0 tutorial)
Because you have to put the result somewhere
You're just adding one and doing nothing with it
At no point in Unity history would this have worked. You cannot store a Vector3 in a float
this?
Yes, that would store the result in the playerScore variable
hmm, from what I can tell, this will just copy the exe to the startup dir on windows, no?
Looks like you're trying to use a script called "LogicScript" which you didn't create
Are you trying to follow a tutorial or something
ooh, could be
yes but my dumbass keeps renaming stuff 😭
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.
yep
What is LogicScript
haven't used windows in a while, does that not work ?
I am not on windows either 💀
Was just reading the code and it seems to copy only the exe to the startup dir.
If I recall that used to work, at least when I was using it back then
odd
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.
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
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
where is this local position coming from?
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
there is no "logcutting1" or "logcuttor" object in this screenshot
I mean to say Logcutting(Clone) mb
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.
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?
what object is this component attached to?
you're using transform, so you're getting the Transform of that object
perhaps you meant to use collider.transform
the Birch_1 object, and yes i know, i tried that when collider.transform.transformpoint didnt work. as you can see in the comment
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
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
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
Hey are you sure your tool handle position in the scene view is set to Pivot and not Center?
that would make things more confusing, yes
Did you check this @humble marsh
ok
I'm going to have to debug more, the issue is sometimes fixed. sorry to waste your guys time, and thank you.
https://docs.unity3d.com/6000.0/Documentation/Manual/ios-detect-game-controllers.html Hi im using this to detect if a controller is connected - if i disconnect my controller its still true
it doesn't immediately update when the controller is disconnected
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..
All definitions of ScriptableObject and MonoBehaviour classes have to be in their own .cs file with 1:1 matching names for serialization purposes right?
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.
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
cool trick: you can use consts in attribute parameters
so you could write Menus.ManifestPrefix + "EnemyManifest"
as long as ManifestPrefix is a const string
oh fair, i could probably through in a nameof there too right
that too
heard chef
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
go through the c# course on the microsoft site
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
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
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
How do I get the vectors perpendicular to the transforma.forward vector?
Cross Product gets a vector perpendicular to the two input vectors
This is a bit tricky in general!
I mean, in this case, you can just use transform.up and transform.right
Thx
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
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
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
Is there a simple way to visualize a RaycastHit2D array?
Loop + Debug.DrawLine
So inside of an update method or make a loop?
Wherever you made the raycast, just add the Debug draw after it.
where I made it or where I'm casting it?
Casting
Debug.DrawRay or DrawLine?
Either will work
Ray will take a point and direction, and line will take a point and destination.
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
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
Do you have gizmos turned off?
You're also using the world origin, so are you looking in the wrong place?
Give it the position of the player for the first argument.
This script is on your player, no? Use transform.position, then.
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
is there a default scene that loads when you launch the game like how does it know which scene to load
Depends on the scene ordering in the build settings
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
If a script has Coroutine running, what would happen first, the Update method of that script or the Coroutine?
It's random by default?
Mmmm, makes sense I guess
can i just not fuck with the skybox when using additive scenes without some hdrp nonsense?
the answers im finding online are insane
Any beginners, DM me, I am working on a cool hobby project and I am looking for people to help me.
If you mean the lighting settings, I think the lighting settings of the active scene are used normally. So you can manually set the scene as active to use it's lighting settings.
!collab
: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
Not sure about that.
thx man
as in your not sure about that or that doesn't sound right?
Both
What setting exactly are you trying to change?
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
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?
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"
Not to overengineer but scriptableobject might also be nice for damage type for other related data, even just visual stuff like icons
It does make more sense, but it's kinda inconvenient to set up when I know for sure there is only going to be 2 types
Also, probably slightly worse on performance??? Not sure
the inconvenience lasts 5 seconds and just makes more logical sense. logical code is good
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and please dont bring up the performance of an enum with 2 values compared to a bool. we're talking nanoseconds differences here
Most things on your code amount to nanoseconds tbh, but on each script on each frame, it does add up
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!
A tool for sharing your source code with the world!
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
i feel like you dont know the scale of a nano second if this is what you really believe. ive seen this repeated by others and really, just no.
stuff like this will NEVER add up to become a performance issue. performance issues in most cases will happen from simply doing too much logic (trying to update 5000 objects per frame)
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?
you're combining transform and rigidbody movement, you should just choose one. i dont see anywhere here where you actually assign a horizontal velocity so the x and z value of your velocity are likely always 0
I don't think it's really that much easier to read, or is it?
not to nitpick but incoming with 1 m and not 2
oh yeah that would do it lol
thanks
you wouldnt be making these claims if you knew more about performance and truthfully i dont think i can convince you otherwise. i do suggest though actually looking into this yourself with benchmarks instead of just repeating the silly statements others say of "it adds up"
Unity probably does one thing stupidly somewhere that costs more than hundreds of those kinda micro optimisations
honestly your code isnt readable at all given that you're forcing the entire if statement on 1 line. id definitely not accept this if i saw it in a pull request
i dont really understand why you wanted to ask on enum vs bool if you were gonna choose a bool for "performance" anyways
