#💻┃code-beginner
1 messages · Page 478 of 1
and yes, I can work in vscode on roblox games
so the 1st game is gonna be probably offline game
my first 50 games are going to be fucking awful
especially since I haven't used C# or unity before
I'm talking about the release game
Never start with a multiplayer game, it adds a whole lot of complexity. Some engines provide automatic object synchronization, in Unity you have to set that up yourself. Some scripts are pre-made for that, but you'll have to roll your own code to synchronize data for your own scripts
yeah
1 man isn't making such a multiplayer game anyway
but with Roblox it's a platform meaning roblox gives you all the users
but with this, it's like we have to make our own platform
I'm on my 500th game xD You get better obviously.
o/
wondering if there are any tutorials for instead of sprite flipping when going in that direction but the sprite faces a targe only on the x axis? wanting to make a 2d combat game but I can't really find any tutorials for this mechanic (they do it in like streetfighter and MK)
child labor ngl
yeah, it is
Yes but also if you sell a Unity game for $10 you get $10
yeah
I made roblox say $1650 in robux; they return me back 24.5% of it
or something stupid like that
they act as if they're the government with the taxes
Well yeah, the servers aren't gonna pay themselves, so they take their cut
Sounds like you wanna just set the rotation, which you can do in many ways. Simplest would probably be assigning what the transform.right should be, that is a direction towards wherever you want it to be
so would it be like a raycast?
Planning on making it like for honor where you can lock onto and off of your opponent and do certain inputs but its linear 2d like a traditional fighting game
Your question seemed like you already had the object you wanted it to look. A raycast is a physics query to get an object or check if an object is in a certain direction.
right okay so
my player looks to the right by default
want to make it so that if it crosses either another player, or whatever its locked onto, it flips so that its still facing that player/ object
If you want it to lock onto the nearest character for example, you could just do a physics query every so often like a overlap box (or whatever the 2d equivalent is) and check what's nearest
hm okay
I'm not really 100% sure how i'd go about that tbh, never dealt with anything like that since i've been stuck in tutorial hell for years
Im not entirely sure what you're trying to do, so it's hard to suggest much. The basics though for locking onto things nearby would include some kind of overlap physics query then get the direction, and set the rotation accordingly. Try it and see how far you get. Many people in here would be able to help if you get stuck
just trying to do the mechanic from traditional fighters where when like one passes another then they still face eachother
I'll try to experiment with it though
private bool Mirrored => (this.position.x < opponent.position.x);
That is how I do it in my fg
OOoooo
oh honestly thats so much easier than I thought holy moly
thanks so much lmao
Np. Also, another important operation is private int FaceDirection => Mirrored ? -1 : 1;
And you can set scale.x to that variable, and use it in math
Ping me if you need any more help coding your FG :)
okay!!! really appreciate it! going to probs be working on the sprites for a while because i'll be able to base hitboxing and timing easier once I get that down but I'll defo let you know!
Gotcha
Although negligible, stuff like this will result in unnecessary calculations if you ever use the values twice. It's better to just calculate it once per tick (whether that be update or anything) and read the value
True. This was simpler and follows KISS, but it isn’t hard to convert it.
https://gdl.space/ehetovidoc.cs I have this monster code that is taking care of the player movement, knife system and gun system....I'm having a really hard time trying to separate in smaller scripts
it is interacting with another code for a inventory manager
but everytime i try to separate in other scripts the equipgun stops working
I wouldn't call it monster code. It's just 180 lines. But it is weird to see knife related logic in a script called TankController. How did it even get there?😅
Idk, things just got out of control....but I'm trying to separate things now...the problem is that the equip gun always crash when I try
Well, then debug it.
when i hold down the spacebar (jump button), the jump height is random (it's not supposed to be random), and the thing being printed is the rigidbody y velocity
link for jumping code (jumpforce is 1200 btw): https://hastebin.com/share/tevesiviqa.cpp
Does collider.ClosestPoint check only the surface or also the volume of a collider?
are you talking to me?
no
its either something with the gravity, or rb1.velocity = new Vector2(rb1.velocity.x, rb1.velocity.y * 1.025f);
not sure why you are changing gravity
since it would create this issue
so it falls faster
stop messing with gravity via script since you are using a RB, instead use the actual project setting gravity
or
change RB gravity on the RB itself
like only once
ok, lemme try that rq
what did you do
i turned all the gravity switching things in the script to comments
and i changed the value on gravity on the rigidbody
(in inspector)
and it's still random
also this doesnt make sense
if (rb1.velocity.y > 0)
{
if (rb1.velocity.y < 12.5f)
{
rb1.velocity = new Vector2(rb1.velocity.x, rb1.velocity.y * 1.025f);
print(rb1.velocity.y);
}
else
{
rb1.gravityScale = 10;
gravity = 10;
}
}
you are checking if the RB Y velocity is more than zero but also checking in there if it is less than 12.5f so this code is useless
also you have a lot of nesting
when the velocity is more than 12.5, i want it to stop going up
you are using a less than sign
not more than
so that code will not do anything
like ever
its contradicting itself
because it goes up when the velocity is less than 12.5, but it stops when it's more than 12.5
no you are not understanding, this code will never run
if (rb1.velocity.y < 12.5f)
{
rb1.velocity = new Vector2(rb1.velocity.x, rb1.velocity.y * 1.025f);
print(rb1.velocity.y);
}
because of the fact that you are checking if the velocity is more than zero, if its more than zero it will never be less than 12.5f, so it will never run
i basically want my jump like hollow knight, where it goes up higher if you hold it for a longer time, but not infinitely
also best look up a tutorial for something like this
if it's between 0 and 12.5, it runs
can't find a tutorial that is like that, except one, but it doesn't make it good
ah a mistake on my part, my bad.
still you might want to fix the nesting
search up "mario jumping in unity"
i just saw like seven tutorials
i don't want it really smooth
wait lemme send a video of what i'm talking about
my internet is so slow
it's sending
i want it something like this
yeah so search this up
its the exact same thing
not really, but lemme watch one rq
im pretty sure hollow knight got inspiration from mario for this type of jumping movement
i finally added it, but it's still random
it jumps 3-7 meters up
when i fully hold it down
opens playtest: doesn't work
re-opens playtest: works
re-opens playtest: doesn't work
i love unity
Conditional bugs are very common and unrelated to unity.
wdym by conditional bugs
Bugs that only happen under certain conditions.
any fix?
Figure out the condition and the cause.
If I'm interested in making a game with Unity, what should I do to start?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thanks!
In a game engine there are a lot of conditions. Some you don't even see or know about. Timing is one condition that often causes bugs hard to reproduce.
it's different every time tho
it isn't a one-off thing
also, start with C# tutorials to learn the basics of programming. either from blogs, websites, or videos . . .
Because it doesn't have to be the only condition.
maybe fps has something to do with it
For example 2 timings or more might need to meet for the bug to occur.
because i'm using delta time
Yeah, frame rate is another possible condition.
but i don't think frame rate would cause a 30% increase
Debug the issue and you'll figure it out.
Why not? Ever heard of the butterfly effect?
nope
It means that even one small change in value could lead to a tremendous change in a complex system.
like a butterfly. stay away from those . . . 🦋
Debug it... It's a good opportunity to learn how to solve issues. Skip it now and you're gonna keep on facing issues that you don't know how to solve
i'm feeling kinda burnt out, so maybe later
If I have prior experience to programming should I still stary with C#?
you'll be fine. anything new you come across is an easy search. you'll mainly deal with syntax errors and specific design architecture problems . . .
👌, thanks
depending how much experience that is, you can skim through c# basics just to make sure u understand it. very similar to java with pretty minor differences if you arent doing anything advanced
Awesome, I have like 2 years of experience with Java on and off
I have this gun script but whenever i shoot the bullet dosent go forward
somewone please help me with this
It should be rotated in the same orientation as the spawning.
The above code doesn't move the object at all.
im realy new, how do i fix it?
Show the !code that moves the bullet
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
idk how to use this?
Show an image of the spawn bullet object.
Specifically we're interested in the inspector.
wdum?
I can't help you if you don't know what an inspector is.
So nothing moves the bulllet.
oh
Show the bullet's inspector
Show the bullet script using the below guidelines - paste all of the code in one of those links and press the save button on the site then copy and paste the url here.
How to post !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Does the spawned bullet move at all?
i would hope so but i guess not
Well, how do you expect it to move if you don't move it?
i did but i guess i was just being stupid
Where?
i have this bit of code but idk how to add it to the other one
Ok, you should be showing together with your initial question.
ok mb
- What are the red underlines? Are there compile errors?
I'm guessing a duplicate script.
I dont think it is red i was just playing around with some settings
There are underlines under the gun and update. Do you not see them?
And take a screenshot of your console window.
sorry sent wrong screenshot
This script doesn't seem to be used at all.
Take a screenshot of the gun object with this script
Why do you have 2 components?
wdum?
What's the difference between Gun and IDKGun?
idkgun shoots the bullet and the normal one adds a firerate so u cant spam shoot
That doesn't make sense. Why split it into 2 components? Also why does the normal gun references the bullet prefab then?
Also, does the bullet spawn point need to be assigned or not?
im realy new to unity and dont know how to merge the two scripts.
wdym? just move the code from 1 to the other
then will it work?
idk the original problem, having them merged/not merged probably wouldnt fix the problem i imagine
ok
Read all of my messages. Maybe then you'll be able to fix the issue.
i did
And you didn't reply to most of them.
Hello friends, I wrote this code in Unity. The code is not visible in the onclick of the button.
just have a monoscripts
you need to make an instance of that mainmenu script
https://unity.huh.how/unity-events/incorrect-assignment if it's unclear
Ah, I see you cross-posted. Please don't do that.
not his fault, he was, incorrectly, redirected here
been working in unity for years and never had this issue, when I have a gameobject attatched to my player and look up and down it warps
anyone able to help me?
probably you have uneven scaling somewhere in your gameobject hierarchy
Hi all, this thing pops up whenever I update my script that I created (not from any package etc), not sure why that's the case. Anyone has any idea?
Have you not read the message?
The script it's referring to is a script I created myself, and I don't believe it's calling any API "that has changed", thus why Im asking
the message also doesn't give much info as I pressed "update any that's found later" and it still shows up after. Thus why Im asking
in that case make a copy of the script outside of Unity, let Unity update it then compare the two
where should i be putting my scripts
what's a bank in Unity?
There's no bank. It was sarcasm.
why are you being rude?
if you don't want to help then don't, and if you are why are you being rude
Because you clearly didn't do any learning. Start with the beginner pathways on unity !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Or read the manual.
that's why i'm here
First learn/make effort, then come with the remaining questions.
Then you wouldn't make that question
If you mean something specific, then clarify, because just "where to put scripts" doesn't make any sense.
where does it tell me where scripts go in the manual
Define what you mean by putting scripts first?
can I make any other service folders except packages and assets
this is what i have
Define "service folders"
That doesn't explain anything.
server handlers
What about them?
yeah that's where they will go
Great. Does that answer your question?
yes
If you're asking where in the assets folder to put your scripts, then you're free to put them wherever you want.
and we can't segregate certain items into folders inside of sample scene
I'm not sure what you mean by that? You can create whatever folders you want.
This is a scene hierarchy. It contains gameObjects. Has nothing to do with files in the assets
You can use empty gameObjects for nesting and grouping other gameObjects. That's not the same as folders though.
okay nice
private void OnCollisionEnter(Collision other) {
if(other.gameObject.tag == "Player")
{
Debug.LogWarning("Hit Player");
}
}```
idk why this isnt working
btw the object in this script is a trigger
do i need a rigid body?
If you give a quick look at the documentation (https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html) you'll see that at least one of the colliding object needs a rigidbody (non kinematic)
i have a trapspike and a player with a character controller which is best to have the rb?
I guess the player in this situation
still doesnt work
is there a possiblity i can import an already existing code or project into unity?
what kind of project or code?
Quick check list :
- Does your player have both a collider and rigidbody ?
- Does your player have the tag "Player"
- Does your trap have a collider ?
- Is your script attached to your trap ?
yes
my player also has a character controller
Wait a second. Does the collider of your trap have its "IsTrigger" property checked or not ?
yes
Then you're using the wrong method. You need to use this : https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
ok but this is my trap that has the script and is the trigger it should work right
Yes.
As long as the collider on your player has its IsTrigger property set to false, it should be fine.
i need to build a space sim project for my class in unity. It has to be interactable too. and i am confused on how to start and completely new to unity.
Yooo thanks so much
that does not answer my question
i am sorry i mean like i see people have moons already in their unity 
is it possible to import the same thur a code or some way?
you still have not have answered the question
a powerful website for storing and sharing text and code snippets. completely free and open source.
this for example^
is it possible to import the same into my unity?
that is a unity script
copy/paste
in?
Generally things are just files in your project folder, so simply dragging and dropping generally works
Do you know how to create a script within unity ?
into the assets folder of your project
nope
i am completely new 
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You'll go nowhere if you don't know how to use your tool so follow these guidelines ^^'
Oh okay
thank u so much again !
@languid spire thank you
+rep
@stiff birch is there a possiblity, u could teach me some aspects?
No sorry, I don't have that kind of free time x)
its alr thanks anyways
IMHO, if you watch this course, you should have a decent base to start messing with Unity a little bit https://learn.unity.com/mission/programming-basics?uv=2022.3&pathwayId=5f7e17e1edbc2a5ec21a20af
It depends.
You'll need to clarify your question
so I have my folders
but each script seems to be the same
like I'm so used to scripts having different functions, server, client and modules
Why did you make them the same?
Are you referring to the MVC design paradigm?
yeah so
we have a client
which has their own set of controllers and client scripts
then we have our middleman which handles data being sent to the server and from the server to the client
and then the server scripts
but how can I replicate this in unity
in my old game engine we had different scripts for the server and client
so I understand now
bydefault unity games are singleplayer, if we want a networking structure, server and clients we have to write it ourselves
or you use one of the many frameworks available to you
well it's probably better to make our own right, so it's relative to our game
if you have the knowledge and experience, yes
is anyone able to help me and my friend with our code it isnt working and we cant figure out why we have been at it for 3 hours thanks!
@languid spire are you able to helop
don't ping specific people . . .
sorry
don't ask to ask. just ask the question and give necessary details . . .
why do I see absolutely no evidence of debugging in that code. Also !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
bro we have been at it for 3 hours this is the most recent code we did and its not working
we have started from scratch and tried to debug different ones
then why are you not debugging it?
irrelevant
if the script is not doing what you expect. you put debugs in there to see what it is doing. This you have not done
It is better to change a value in Unity or in the code ?
For exemple the Jump height in a platformer, should i write ```cs
public float jumpHeight;
Or
```cs
public float jumpHeight = 233f;
your no help thanks mate
In Unity, once a value has been serialized changing the code will not cange the value
I mean, what's the best to do. It is better to change the value in code or don't specify it and change in the Unity Editor
in the inspector, it is the ONLY way to change a serialized variable
How do you expect us to help you. We have no idea of the values of the variables your code is using and, because you have not debugged it, neither do you
They are, and if you don't know what they mean then ask for more information rather than repeating yourself.
Debugging is a very basic skill that you can start off with and it is incredibly helpful.
fixed myself dont @ me again
Good luck with your project 👍
I dont know if I can write this type of question here but yeah. When I write something in an inputfield and then delete even a single letter, the text shifts all the way to the left. Does somebody know why?
What do you mean shift? By default text starts on the left, no?
Maybe you have a video?
thanks you where more help then Steve
I do, one second
Consider accepting the tips that others give you in this channel, or don't bother asking for help
@burnt vapor
Do you modify the input's properties in code by any chance? Perhaps you can share those scripts
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
no
I just grabbed it
Is there some property like padding that happens to change?
can you describe where to look ab this padding?
resolved it
Greetings, would anyone be able to help me set up a basic AR system?
This is my first time working with AR, I've been trying to get something to work for weeks but I've had no success. No tutorial or forum I've followed has been of any help.
I would please just like help to come to understand how to work with it, and how to set up this system.
The system needs to do the following:
- It should be able to be turned off and on.
- Using the Mobile Phone's Camera, and it should look for a picture, and then project a 3D model onto where the picture is.
Please, any help would be greatly appreciated.
if(other.gameObject.tag == "Player")
{
if(TrapSpikeUp.SpikeUp == true)
{
other.GetComponent<Health>().CurrentHealth -= PlayerDamage;
Debug.Log("Hit Player");
}
}
}```
this is a spiketrap script is there a way so that it doesnt deal damage every millisecond when i stay in the trap
and instead it has a cooldown
Have an invulnerability timer in the health script
Ideally, you'd evaluate it in your current health property
Start a coroutine in OnTriggerEnter and stop it in OnTriggerExit
Or just set a bool and use FixedUpdate
What happens to a coroutine if the gameobject its attached to is destroyed? Does it stop midroutine or finish its iteration?
It would immediately stop
Wait till the end of the frame to destroy?
Or delay 0.01 seconds or something
Destroy(gameObject, 0.01f);
what if there were a couple of WaitForSeconds in there though :x
Fire a new coroutine that would wait till all of the others were finished 🤷♂️
Where you'd have a reference to the other coroutines and would flag their loop false with a variable when wanting to terminate them by natural/normal means.
Multiple solutions possible :
- coroutine that start when entering a trigger and stop when exiting a trigger as PraetorBlue said
- a member variable to handle the delay with Time.time and a simple comparison like below
private float nextDamageTriggerTime;
private float damageTriggerDelayInSeconds = 1f;
private void OnTriggerEnter(Collider other)
{
// Do stuff
nextDamageTriggerTime = 0;
}
private void OnTriggerStay(Collider other) {
if(other.gameObject.tag == "Player")
{
if(TrapSpikeUp.SpikeUp == true && Time.time >= nextDamageTriggerTime)
{
other.GetComponent<Health>().CurrentHealth -= PlayerDamage;
Debug.Log("Hit Player");
nextDamageTriggerTime = Time.time + damageTriggerDelayInSeconds;
}
}
}
what is the different between unityengine.random and system.random?
Have you checked their docs pages to see?
The most significant difference is System.Random expects you to make an instance of it, and UnityEngine.Random operates entirely with static methods.
oof readding the docs now thank you
Your code makes no sense...
TimeToSpike = 0f;
DamagePlayer();
private void DamagePlayer()
{
TimeToSpike -= Time.time;
if(TimeToSpike == 0)
{ ```
By the time you do cs if(TimeToSpike == 0) It is ALWAYS going be equal to - Time.time
which btw you probably meant to use Time.deltaTime, but even that doesn't make any sense here
you're:
- Setting TimeToSpike = 0
- subtracting Time.time (or deltaTime)
- Then checking if it's 0???
Think about your code for a minute
it will not work
x = 0;
x -= 5;
if (x == 0)```
Will this ever work??
Thnk about it
that's what you're doing
Hello,
Is it interesting to use namespace in Unity or not ?
interesting?
"interesting" is completely subjective. But no I don't find namespaces interesting any more than I find hammers interesting. They are tools, to be used when you have a specific task in front of you.
I follow a course of C# and found namespaces. When I see it, I don't see the utility in Unity but I ask if it interesting to use it in some specific situations
Interesting is completely irrelevant. You don't do certain coding practices because it's "interesting".
Are they useful? Yes, they can be. Are the necessary? Not always, no.
Ah, I think you mean useful.
For single small projects, not really
For large code bases it can help in convenience
For multi-project, modular systems, they are very useful
Also, if you are making assets, they are required
Namespaces are not necessary for most people because they are not working on large systems where some organization is required or to prevent naming conflicts, but I recommend using a namespace for your scripts . . .
Even without large scale project, if you want to have reusable code across your projects with name that can be, well, common, I find it useful to isolate your code in namespaces to prevent conflict.
!help
{
private float lastTimeFired;
public float chargeTime, maxDistance;
private Camera cam;
private void Start()
{
cam = Camera.main;
}
private void Update()
{
if (Input.GetMouseButtonDown(0) && CanFire(lastTimeFired, cooldown))
{
StartCoroutine(FireDelay());
lastTimeFired = Time.time;
}
}
public override void Shoot()
{
RaycastHit hit;
Vector3 dir = (MousePos - transform.position);
Ray ray = new Ray(transform.position, dir);
Physics.Raycast(ray, out hit, maxDistance);
Debug.DrawRay(transform.position, dir, Color.red, 50);
print(hit.collider.gameObject);
lastTimeFired = Time.time;
}
private IEnumerator FireDelay()
{
yield return new WaitForSeconds(chargeTime);
Shoot();
}
}
This direction just goes wherever it feels and i have 0 clue why
{
get
{
Vector3 mousePosition = Input.mousePosition + new Vector3(0, 0, -1);
Vector3 position = Camera.main.ScreenToWorldPoint(mousePosition);
return position;
}
}```
thats the code for the mouse position
and my camera is in orthographic
why is Inputs not recognised in here, but it is in a different script?
Inputs is an auto generated class
from the new input system
did u put using unity.inputsystem or whatever
Your mouse Z is not zero
Let your IDE suggest what namespace to import
@celest holly With ScreenToWorldPoint the Z value is at your camera's position (or its near clip plane)
ohhh my god of course
they dont have it as an option. this script doesnt recognise unityengine.inputsystem as a namespace eitehr
Hover over the Inputs type in the other class. What namespace is that type in?
You might also have assembly definitions excluding the namespace Inputs is in from this script's assembly
{
get
{
Vector3 mousePosition = Input.mousePosition + new Vector3(0, 0, -1);
Vector3 position = Camera.main.ScreenToWorldPoint(mousePosition);
Vector3 finalPos = new Vector3(position.x, position.y, 0f);
return finalPos;
}
}```
put it to this and its still broken
still coming from the sky
it might be cus im using photon quantum and im in the photon folder which might exclude some things? idk im going to go ask them
If they have assembly definitions in those folders, probably.
How exactly is it broken?
Are you using 3D colliders and rigidodies by the way? Your game logic seems 2D but you are using Physics and not Physics2D
Oh. Your world is in the XZ plane, not XY plane
I assumed it was side-view because of your code
oh so its y that needs to be 0 and not z?
meant to mention
this is whats inside it
thank you osmal ive fixed it now
In this case I think you should shoot a ray from the camera instead. Create the ray with Camera.ScreenPointToRay(Input.mousePosition)
Then shoot from your character towards that hit point
Make sure to check the bool that Physics.Raycast returns, though
oh okay
{
get
{
Vector3 mousePosition = Input.mousePosition + new Vector3(0, 0, -1);
Vector3 position = Camera.main.ScreenToWorldPoint(mousePosition);
Vector3 finalPos = new Vector3(position.x, transform.position.y, position.z);
return finalPos;
}
}``` this seems to be working for it though
is it neccessary to rewrite it?
I think that only works if you are viewing from the top
If that's how your camera is then yeah sure
yeah my cameras always facing down
Is it orthographic or perspective?
Alright then it should be fine
okay thanks for the help
more info
https://unity.huh.how/screentoworldpoint
Hey guys. I'm just working on a flappy bird clone project, right now I'm having an issue in my pipe spawner script (The object of type 'Transform' has been destroyed but you are still trying to access it. Line 78). I think what's happening is the ManagePipes() function is deleting pipes as they go off the screen and for some reason MovePipes() is still trying to move them. https://hatebin.com/dldhnwwofu
you're still holding a reference to something destroyed
one of the pipe in currentPipes was destroyed yet you're trying to access its trasnfrom, since its still in the array/List
but managePipes() is called after movepipes()
so wouldnt the list be updated by then
by the next frame
assuming you're cleaning the correct objects in the list
currentPipes.RemoveAt(currentPipes.Count - 1);
currentPipes.RemoveAt(currentPipes.Count - 2);```
This is likely wrong
after you delete the last pipe in the list, the last one will again be at currentPipes.Count - 1
if you want to delete the last two pipes you would do
currentPipes.RemoveAt(currentPipes.Count - 1);
currentPipes.RemoveAt(currentPipes.Count - 1);```
because removing one changes the count
ohh that makes sense let me try it
You can also use this: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removerange?view=net-8.0
i.e.
currentPipes.RemoveRange(currentPipes.Count - 2, 2);```
that will likely be the most efficient way.
this doesnt work actually
I get the same error as before
oh wait nvm
yes that does work and is a better way to do it thanks 👍
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine
public class Exemple : MonoBehaviour
{
public bool Something = false;
void Update()
{
Debug.Log(Something);
}
}```
why by having these code, I got in the console, true?
and only by adding the start function and set the bool value to false it goes to false?
What is it set to in the inspector
The inspector takes precedence over the default values in code. This is so you can change the value on specific instances
Is there a way to write this more cleanly?
public void GetDataFromStage(GameObject stageButton)
{
StartPlanetInt = stageButton.GetComponent<StageButtonData>().StartPlanetInt;
FinalPlanetInt = stageButton.GetComponent<StageButtonData>().FinalPlanetInt;
hasComets = stageButton.GetComponent<StageButtonData>().hasComets;
}
something like this for example:
public void GetDataFromStage(GameObject stageButton)
{
Something data = stageButton.GetComponent<StageButtonData>();
StartPlanetInt = data.StartPlanetInt;
FinalPlanetInt = data.FinalPlanetInt;
hasComets = data.hasComets;
}
pass the component instead of a GameObject . . .
why are you using the GameObject in the first place? You should be using the component through out without needing the GetComponent
then you can access the data from the component. there is never a reason to use a GameObject type . . .
not quite true, if you only use SetActive or other GameObject properties/methods
yeah, i was going to mention that as it's the only case . . .
but at that point, if you already have a component, you can just do component.gameObject.blah . . .
But if you have an empty GO? I suppose you could use Transform instead
public void GetDataFromStage(StageButtonData stageData) {
StartPlanetInt = stageData.StartPlanetInt;
}```
exactly. GameObject gets the cold shoulder . . .
Yep I just did that and it worked and now I am speechless...
I'm having a hard time accessing the TileBase from a TilePalette to build a tilemap with script using Tilemap.SetTile(). The documentation in unusually terrible for Unity for this system. Anyone have any good links or advise?
you don't need tilepalette to place tiles
just make a reference[SerializeField] Tile myTile n drag it in.
then simply TileMap.SetTile(tilePos , myTile)
even if you did pass the GameObject, cache the component to a local variable and use that
public void GetDataFromStage(GameObject stageButton) {
stageData = stageButton.GetComponent<StageButtonData>();
StartPlanetInt = stageData.StartPlanetInt;
}```
though, using the previous method is better . . .
i was looking for exactly this
but this one is even better
I came looking for copper, but found gold
Thanks a lot!
so i'm trying to rotate a gameobject 5 times, with a little gap in time between all of these times, for a full 360. The way i'm doing this is using a while loop in a coroutine that will stop once the object's y rotation reaches the target, and inside the while loop there's a smoothdamp for the objects transform.rotation, thing is, it keeps freezing the project once it runs the coroutine, i dont think its an infinite loop so what is it? (my code is in another language, hold in while i get it here in english)
{
observing = true;
for (int i = 0; i < 5; i++)
{
float targetRotation = transform.rotation.y + 72;
velocity = 0;
while (transform.rotation.y != targetRotation)
{
transform.rotation = new(transform.rotation.x, Mathf.SmoothDamp(transform.rotation.y, targetRotation, ref velocity, 0.5f, 10, Time.deltaTime), transform.rotation.z, transform.rotation.w);
}
yield return new WaitForSeconds(0.75f);
}
if (!targetFound) { yield return new WaitForSeconds(2f); }
observing = false;
}```
Well, that while loop's gonna run to completion instantly, and if it happens to not be able to reach targetRotation, it'll never stop
Also, what are you hoping to achieve by manipulating a quaternion directly like that?
That's gonna produce a really weird orientation
i've thought that maybe it wouldnt get to the exact value of targetRotation so i put an if statement so if rotation gets less than 0.1f and more than -0.1f from the targetRotation it would set it to the targetRotation, but it didnt work
just want it to smoothly rotate the 72 degrees, wait a bit, and repeat 4 more times, i thought that smoothDamp had to be repeated a bunch of times so i used a while loop
If you want to rotate in degrees you should be changing euler angles, not .rotation
.rotation is a Quaternion, a normalized 4D vector. Human minds were not meant to manipulate those numbers directly
so, do transform.Rotate and move it to work in Update only if (for example) a bool is activated in the coroutine?
This isnt a coding question, but I added volume n bloom so an gameobject can glow, but its applying to the skybox sun too. How would I go about removing bloom from skybox and only have the gameobject glow. The 2 camera method didnt work
im using urp
I can upload a photo if needed
i was trying to make it so that the time reset when the function is run
The function runs every physics update, so that doesn't make sense
You should make it reset when you first touch the spike, right?
That's what OnTriggerEnter is for
hey um im kinda dumb why isnt this working?
because you dont have a class called LogicScript
Does anyone have any meta development experience?
I need help getting contents of a assets folder dir, and writing storage to the SD/game dir
doesn't sound like a Unity problem
yeah but it's a coding error, which I need help for 😭
I'm about to send script
using System.IO;
using UnityEngine;
using CraftSharp.UI;
public class QuestAppdataSpoof : MonoBehaviour
{
public LoginControl client;
void Start()
{
if (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageWrite))
{
UnityEngine.Android.Permission.RequestUserPermission(UnityEngine.Android.Permission.ExternalStorageWrite);
}
CopyMineproxyFiles();
}
void CopyMineproxyFiles()
{
string sourcePath = Path.Combine(Application.dataPath, "Dependencies/Mineproxy");
string destinationPath = Application.persistentDataPath;
CopyDirectoryContents(sourcePath, destinationPath);
TryConnectToServer();
}
void CopyDirectoryContents(string sourceDir, string destinationDir)
{
DirectoryInfo dir = new DirectoryInfo(sourceDir);
if (!dir.Exists)
{
Debug.LogError($"client dir does not exist: {sourceDir}");
return;
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string targetFilePath = Path.Combine(destinationDir, file.Name);
file.CopyTo(targetFilePath, true);
Debug.Log($"loaded file: {file.FullName} to {targetFilePath}");
}
DirectoryInfo[] dirs = dir.GetDirectories();
foreach (DirectoryInfo subDir in dirs)
{
string newDestinationDir = Path.Combine(destinationDir, subDir.Name);
if (!Directory.Exists(newDestinationDir))
{
Directory.CreateDirectory(newDestinationDir);
}
CopyDirectoryContents(subDir.FullName, newDestinationDir);
}
}
void TryConnectToServer()
{
client.TryConnectServer();
}
}
If anyone can help, this would be greatly appreciated; I've looked online for a solution already with none found.
You should explain what the issue is
^^ ??
assets folder dir
are you referring to the Assets folder within your project? because that does not exist in a build
Is there any solution to this without downloading files from a server?
What problem are you trying to solve
what is the actual intention of what you are attempting to achieve?
https://xyproblem.info
What is the purpose of trying to read data from assets
To do what??? Explain your issue if you want help
- ' getting contents of a assets folder dir, and writing storage to the SD/game dir' I don't know if I simplified this enough.
Importing everything in one directory
(assets/dependencies/mineproxy)
To
(sdcard/Android/data/com.Exotic.Mineproxy/files)
I have write permissions set up correctly, and only just the base folder seems to be going over.
for what purpose
any advice on learning c#?
Well, as stated, the Assets folder ceases to exist on a built project
so there is no folder to read the contents of
pretty simple really this
string sourcePath = Path.Combine(Application.dataPath, "Dependencies/Mineproxy");
should be using streamingAssetsPath but... Because this is an Android build you need UnityWebRequest to read it
so that a proper solution to what you are trying to achieve can be suggested because as i've already pointed out the Assets folder does not exist in a build
And I've asked Is there any solution to this without downloading files from a server?
A solution to what
alright i'm done engaging with this conversation because you won't provide any useful fucking information
You've asked a solution, not a problem
Dawg idk how to dumb it down enough for yall 💀
The solution you're asking about is non-viable. We cannot provide alternatives because we don't know what the problem is
Yo chatgpt is actually more reliable even when it comes up with shit ong
server is garbage
best of luck with that
So I'm making an ultra simple 3d car controller script. I have the simple movement and turning working but I want to make so that the vehicle turns the opposite way when reversing (like a real car does) instead of still rotating the same direction, if you can understand my poor explanation. I tried to do this by multiplying by turnSpeed variable by -1 when the forward velocity is negative and resetting the variable when the speed is 0 or greater by multiplying by Math.Abs but this made the turning quit working completely. Can someone here please show me a solution to this? Also if there is a good way to get rid of the if statements in my code I would appreciate those tips as well!
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float speed = 1f;
public float turnSpeed = 1f;
bool canTurn;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
rb.velocity = transform.TransformDirection(0, rb.velocity.y, vertical * speed);
if (rb.velocity.z != 0)
{
canTurn = true;
}
else
{
canTurn = false;
}
if (canTurn == true)
{
transform.Rotate(Vector3.up * horizontal * turnSpeed * Time.deltaTime);
}
}
}```
people won’t want to help you if you’re just being an arse
Ever hear about "Theory of Mind"? The concept that a different person has entirely different perceptions to you, and that they possess different knowledge than you? Most humans develop a theory of mind at about two to three years old
You can stop this conversation, I've given him the answer to the question he has yet to ask
have you considered that it is actually your attitude and lack of explanations of what you actually want to achieve with this that is garbage?
But every now and then, someone doesn't. Then they post here
How are you handling the turning? Since your reverse velocity is backwards, as the object rotates, it should just work with reversing directions like a normal vehicle
Shouldn't need to invert it at all
When I reverse and press D (the key that turns right when driving forward) the car rotates clockwise which is the opposite direction of what it should rotate in a real car if you steer right while reversing
probably another stupid mistake but i cant figure it out
What's the error say
remember C# is case sensitive
Yeah It's alright I literally just put it in the recourses folder
the only thing close to helpful anyone came here was reminding me that the assets don't build when compiling.
If your turning code is actually rotating the object, then it should just do that. You'd be rotating your forward direction to the right, and since your reverse velocity is the inverse of forward, it'd be rotating that direction to the left
So thanks for whoever said that
how do i make a teleporter script for my fps game?
Literally everybody said that
best configure your !ide if you did not spot that
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
And if you had said what you were trying to reference from disk, we might have suggested Resources
you wont be able to read from there either in an Android build. See my earlier post
okay
but I have no code that links my velocity to my turning?
TransformDirection
so how do I get it to rotate the opposite way when reversing?
As I said, if your turning code is actually rotating the object, then it should already be doing that
well it doesn't
Which is why I asked how you were doing the turning and you haven't shared it
you can see my code can't you?
you are much less likely to actually receive help if you post photographs of your screen instead of sharing !code correctly or using screenshots
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ah, I see, I didn't think you were using horizontal anywhere, but I missed it in the last line
I thought it was being used further down and was cut off, my bad
sucks for you then
put an internet card into your pc
thats what I do
use ur cellphone as USB tether
connect the phone to the PC and piggyback
tada 🪄
I think it might be that you're rotating the transform, not the rigidbody. You might need to use Rigidbody.MoveRotation or rotate it via AddTorque instead.
ok I'll try that thanks
you have come here asking for help therefore it is your responsibility to make it easy for us to help you. If you cannot be bothered to do that then you can hardly expect us to help you
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I already had all of these steps done.
but it still didnt show me or correct me
Start rewriting the line and it will show suggestions as you type and you'll see the correct method
@polar acorn I googled and looked up the doc and stuff and I still can't figure out the syntax 😭 can you help plz?
the method expects a quaternion.. ur feeding it a vector3..
look up how to convert vector3 to quaternion.. and give it the right type of value
the errors a give-a-away.. cannot convert blank to blank
MoveRotation takes a Quaternion that is the destination rotation, while transform.Rotate took an amount to rotate by. I believe you can rotate a quaternion by multiplying it by another. So you'd need to convert that amount to a quaternion, and multiply the current rotation. So you'd do rb.rotation * Quaternion.Euler(Vector3.up * horizontal * turnSpeed)
ah makes sense
lemme try
MoveRotation is also not static, you need to call it on your rb variable, not on the Rigidbody class itself
ohh true ^
Ah, good call, I missed that
can i join in the convo as well?
so that last line you gave converts a quaterion to a vector 3 and assigns it to a variable? I might be confused lol
Quaternion.Euler(Vector3.up * horizontal * turnSpeed) converts your rotation amount into an orientation. You "Add" orientations by multiplying them. So, your current rotation times that should apply that rotation to your current rotation
That whole section would be what you'd pass to the MoveRotation function
ah ok
so something like this?
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * horizontal * turnSpeed));
the red squiggly lines went away so I must have done something right 🥲 (this is a joke)
@polar acorn
Yes. I think that's how Quaternion multiplication works?
Quaternions are wizard numbers I tend to just futz with them till it works
That one wasn't sarcasm that's lack of confidence in my own understanding
ok it works but it still doesn't turn the right way when reversing
here is my updated code:
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float speed = 1f;
public float turnSpeed = 1f;
bool canTurn;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
rb.velocity = transform.TransformDirection(0, rb.velocity.y, vertical * speed);
if (rb.velocity.z != 0)
{
canTurn = true;
}
else
{
canTurn = false;
}
if (canTurn == true)
{
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * horizontal * turnSpeed));
}
}
}
my car controller uses the Vertical input multiplied into the Rotation..
when ur going forward its 1.. soo anything multiplied with it is what it is (this is normal steering)
when ur reversing its -1.. soo anything multiplied with it is reversed (this is reversed steering)
this automatically makes it work right out the box..
oh that's a good idea actually
yessir, then u only need to make ur steering work (going forward) and if it does it should work w/ reverse just by multiplying the vertical input in w/ it
It works!!!
thank you bro
it already feels more like a car now
just gotta add my blender model I made
Hi. I have a resource cost Monobehaviour class to manage my resource costs for building/crafting etc. I have the resource cost on my item to build. Set the cost in the inspector. All that works. My inventory also works with the resource cost. The way i place a building part is to ResourceCost cost = pendingObject.GetComponent<ResourceCost>(); the it sees if i have the resources available then places itor doesnt. I have made scriptable objects for my crafting recipes. I got it to work if i make the Resource cost not a mono behaviour but just a class. But this ruins my building manager as it requires get component. How can i show the resource cost in my inspector for the scriptable object as a monobehaviour or how can i access the resource cost in the building manager if it isnt a monobehaviour? I'll send examples
why not just make the cost in the scriptable object?
Do you mean like this?
yeah i guess, or if you say you have "recipes" then surely that should just automatically detect what you need?
if not then yeah just putting the cost like this should be fine i think
how can i get the faced direction of a 3d object?
transform.forward
this works for the crafting side but ruins my building side of stuff as it isnt a monobehaviour anymore.
just get the cost from the scriptable object
so is
directionToMove= Vector3(transform.forward);
valid?
No. This isn't python
And it's already a Vector3
what is the correct way of doing it then?
oh alright, thanks
even if you were to do that, you would need new Vector3
yeah i missed out new, i already have that just didnt add it when typing it across to discord
So I should make my building items *walls, floor etc) scriptable objects too? I'm not sure what you mean
do you have a reference to the CraftingSO that you are placing? just get the cost from that
what if i add velocity instead?
like add the movement velocity to the current velocity
u could probably do that too..
AddForce with transform.forward OR AddRelativeForce with Vector3.forward
Pretty straightforward, no pun intended
Use AddForce and pass in transform.forward multiplied by some amount of force
transform.forward multiplied by some amount of force
Do you know how to call a function
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You call that function and pass in the parameter I said
🫣 Function (Parameters) ;
I literally gave you the exact answer
I told you what function to call and what value to pass it. Then when you said you didn't know how to call a function, I sent you how
rb.Function
to be exact
Function w/o a prefix would call a method within the same class..
but ur lookn for rigibody stuff
next time please !learn how to use unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
we wont spoon feed you next time
hey guys I am using a dictionary.. I want to have set already some waves for my game .. each wave with dif enemies and quantities.. but it seems very hard to access from another script these values.. is there any other easier way?
example: wavesDictionary["Wave2"] = new Dictionary<string, int>{ { "Circles", 7 }, { "Squares", 2 }, { "Total", 9 } };
Make a class or ScriptableObject for Wave and give it int parameters for TotalCircles, TotalSquares, etc., and make a dictionary of that
hmm.. ok, might be a good idea. I will check that. Thank you
if (boatController.drivingBoat)
{
yRot = Mathf.Clamp(yRot, boatController.transform.eulerAngles.y - 90, boatController.transform.eulerAngles.y + 90);
}
my camera snaps when turning boat, i realize its becuase quaternions are weird and values goes back to zero but idk how to fix D:
Might want to provide more details on what you're trying to do and what happens actually. A video of the issue would be helpful. As well as sharing all the relevant code.
so when youre turning in your boat ( just a simple setup ) im setting a clamp on camera, when you turn boat ( as you can see im using the boats rotation for the clamp ) past 360 degrees, it snaps back to 0 causing an ugly snap in game, which is to be expected, i get whats happening. Just wondering if anyone knows a better solution.
A better solution might involve rewriting your whole rotation logic. Which is why I'm saying that we need more details.
sure, here is a video of what i just explained. Let me know if anything else could be of use.
float xInput = Input.GetAxisRaw("Mouse X");
float yInput = Input.GetAxisRaw("Mouse Y");
yRot += xInput * _sensitivity;
xRot -= yInput * _sensitivity;
xRot = Mathf.Clamp(xRot, -90, 90);
transform.rotation = Quaternion.Euler(xRot, yRot, 0);
playerOrientation.rotation = Quaternion.Euler(0, yRot, 0);
this is the only code thats rotating anything.
How are you rotating the boat?
not techinically rotating, i guess could be considered, but im applying force for forwards and sideways at a specific point where in real life a motor would be.
rb.AddForceAtPosition(-sideDirection * turnSpeed, turnForcePos.position, ForceMode.Force);
I see.
First of all the ideal solution would be to use cinemachine
Tested here but with SO I will need to create like one SO for each wave.. I need something that I have already preseted in 1 script.. all the waves there,. Imagine it will be 100 waves.. cant just do 100 SOs.
can you show us what sideDirection is?
side direction and the way im driving boat are irrelevant. thanks anyways guys, ive solved the issue using angle axis instead of trying to clamp floats.
You do 1 SO and make 100 instances of it
damn that is too much hahaha
If you have 100 waves you're going to need 100 of something
You can't store data on nothing
What have you preseted?
I am actually at the end using a dictionary. its working as intended. Even tho not sure if the best way or optimal. THank you 😛
doing something like that:
There are so many ways to do what I want to do. Hard to pick one
And prob game will have 100 waves or more.. each one to be balanced, I need to do them manually and not just random.
still thinking ways to optimize that. will not go forward until I find a good solution
will keep only 2 waves until I find best way to replicate that to 3..4....100...
That's wild. Why not use a WaveData struct, class, or SO containing a list of enemies?
Is there a particular reason you're needing strings?
You can have an SO containing a list of WaveData (all of your waves) where each instance in the list has its list of enemies. There is no need to store the total, as a list — or any collection — keeps track of its size . . .
I want to confirm that this```
[SerializeField] private TileBase test;
public void DrawTiles()
{
baseTiles.SetTile(new Vector3Int(0, 0, 0), test);
baseTiles.SetTile(new Vector3Int(0, 1, 0), test);
}```
Doesn't work because each 'tile' needs to be created individually from a prefab or something?
because that would make no sense whatsoever given that a tile is a scriptable object.
just try it
should work but easy way to find out
there SO's so assumeing all it needs is the reference to the asset and not a instance
tiles are just scriptable object "assets"
when you dragged the tiles onto tilepalette it asked you where to place them
I did, still nothing, The documentation is not up to unitys normal standards, I'm assuming because most people do not script their tile system
The tiles will only be placed during runtime
you didn't use tile palette yet ?
I cut a sprite into tiles
assuming they made tiles already, and they jsut want to build things procedurally
SetTile works exactly once
it works as many times as you call it
I personally would also not use BaseTile. Just inherit Tile class you can make custom tiles
will check that
well yes and no.. but yes because I need to give a String to the method that Instantiate to say who is going to be spawned and the amount.
I have tried that as well. This code creates one tile, not two tiles. https://hatebin.com/zbvgsdzqac
hmm should work fine. How do you call drawtiles?
In the start function of a LevelManager game object.
make sure you saved and its a new version of script try changing pos
pos?
oh god, yeah obviously
hmm, so no matter what I do it looks like all tiles are only being drawn on one square
regardless of position
The TileMap im targeting has an XY orientation though
does RefreshAllTiles help after setting some tiles
is that changed or the default ? its been a while
SetTile should automatically refresh the board
I didn't touch it from default.
can you show wat it draws in the scene ? showing inspector for the script
do you have a grid component btw
You know what
I did, but when I dragged the grid > tilemap to be a child of a manager it lost its hierarchy and I didnt realize it
let me fix that and test
yeah i normally just make the the tilemaps all childern of a grid
it can't figure it out otherwise since it is aloud to have multiple grids
well its burnt into memory now to check for that next time
Hey, I had a question if anyone has a moment to help me with something.
don’t ask to ask
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
lol I suppose so... I just feel very stupid about this coding stuff.
we all start somewhere
I am trying to make a flappy bird clone to learn coding from this great video.
But it keeps telling me I haven't assigned something in my script and I have no idea why.
well then assign it 😉
thats probably because you havent
I don't know what that means though :X
would need the exact error but could be a few things
well start by showing us the exact error with a screenshot
good chance you need to just drag something into the script as a reference
Okie dokie! Give me a second.
well its either in the inspector or in the script, if its in the inspector please drag and drop what it wants, if its via script just use Getcomponent to grab the item it wants
i’m using AddForce to move a 3d object. i’m trying to get it’s current direction of travel during runtime.
i’m doing this so that i can tell it to rotate to face away from it’s direction of travel.
use the rb velocity
rb.velocity
got it
and this returns a vector i assume?
it is a vector yes
thanks!
select the bird object and look at the inspector
ok so the script on the bird gameobject, needs it assigned
Okay, how do I assign it?
OHHH
This link is super helpful.
❤️
Wait.
Let me read more, that didn't fix it.
ok show that its assigned
you have a copy maybe on Main Camera
make sure you aren't doing something like overwriting the assignment in Start or Awake
seems ok
and yeah, make sure you don't have another copy of the component in the scene
i mean theres not a lot to rewrite
Like I deleted the whole script, came back here, rewrote it the way he said, then was like "I need backup" and came here.
why?
can you show the current script
just update your script
Sure!
since the one instance you showed looked fine, make sure its not attached to a other game object
Hello! I am making a simple open world 3d car game and I have made a working car controller script (with the help of a few people here) but the acceleration and braking is instant. I want it to ramp up slowly and preferably coast when I let off the gas (until I hit the brake of course). How would I go about doing that? Here is my super simple script so far:
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float speed = 1f;
public float turnSpeed = 1f;
bool canTurn;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
rb.velocity = transform.TransformDirection(0, rb.velocity.y, vertical * speed);
if (rb.velocity.z != 0)
{
canTurn = true;
}
else
{
canTurn = false;
}
if (canTurn == true)
{
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * horizontal * vertical * turnSpeed));
}
}
}
well you are setting the velocity of the vehicle directly
best use addforce()
ok yes I figured something like that might need to be changed
make a Z float speed for your velocity if thats ur forward/back then do Mathf.MoveTowards or do vector3.MoveTowards with velocity
ok so did you clear console and start game again
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
No! I didn't know that was a thing.
configure your ide
make sure you did assign it like you shown , if its still errors check the camera if you didnt put another copy of that script
I think I'll have to write down a lot of these words you guys are using and look them up so I can understand better.
Because I am very confused at what is being asked of me and I think it is unfair to ask for help if I don't know the language :X I apologize guys.
I woud suggest checking pins in this channel
and !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
especially the Essentials pathway
its setup correctly already
I'll look at that then.
i dont think so, all white does not mean set up
pretty big giveaway
Me and friend are trying to learn this stuff because finding a programmer is hard xD
well you found us
Assembly-CSharp so its aware of the sln and csprojs
then explain why its all white
everyone is always looking xD
clearly something is wrong
xD Well, sure. Finding programers who are alive is easy. Finding programmers who want to work on your game, on your schedule, for free well, that isn't like under 18 is pretty hard.
it may know what it is but its not actually using it
unless they took a picture as soon as CS opened
that would explain it
time is money the older you get the worse it gets 😛
well thats to be expected programmers have there own ideas to work on too
You can always post on reddit and the likes, there's always people looking for projects to collab on.
Provided you have something worth showing to entice people to join up. Most won't do so blindly.
you can also !collab if needed
: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
very tru
You're telling me! I have time to learn.
if you have time thats all you need tbh
the resources are plenty and they are free
I'm assuming you're using dictionaries because you're wanting O(1) read but it looks a bit excessive to use so much.
If you're just needing a reference to waves, you could probably just reference the SO with the waves. If you're wanting different combinations, you could either have them premade as SOs or perhaps just have a list of the enemies as a wave and reference data from the wavesSO.
i guess you will be our frequent customer, welcome and keep this page on standby!
yes its by far one of the easier and least costly skills to learn
it can cost sanity if you let it 😛
Yeah I am trying to do some tests with SO to see.. but I will need to create a lot of SOs.. lets see
Yeah, I just keep getting errors on my projects and don't know what to do. So the unity site should help though hopefully.
only if you let it, its no where near as deep learning wise other skills
its because you're jumping into it without a base to start with, what you're doing is already complex without introducing you to the tools at your disposal, components, etc
yeah if you let it, but I wouldn't say everyone can learn it, still takes quite a bit of critical thought
yeah keep your idea in mind, but start on some introductory learning content
what good is a fisherman without his pole? is the best way to explain this
its hard to know what to do with out a grounding first
some cheese words "its a marathon not a race"
@steep rose alright so I figured out how to implement AddForce and it works but the other part of code that I came up with isn't working how I want it to (surprise surprise). When I am pressing a gas or brake input it lets me turn but when I let go of the inputs and keep coasting/sliding, it doesn't let me turn anymore, despite the purpose of my code being to allow me to turn when the forward velocity is not 0. Do you know why this is happening?
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float speed = 1f;
public float turnSpeed = 1f;
bool canTurn;
void Update()
{
Vector3 forwardDirection = rb.transform.forward;
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
rb.AddForce(forwardDirection * vertical * speed);
if (rb.velocity.z == 0)
{
canTurn = false;
}
else
{
canTurn = true;
}
if (canTurn == true)
{
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * horizontal * vertical * turnSpeed));
}
}
}
You guys are really nice ^___^ next time I'll be better
you should not use == with floats
I'm gonna head to bed. Thanks again everyone.
I tried it inverted with != but that didn't work either
can use Mathf.Approxmentaly
or test how close it is to zero and decide what is good enough
actually this is because you are not using local velocity
ive had this before
with my game in particular
as soon as you turn im guessing you cannot turn again?
I can turn when pressing forward or backward inputs but not when I let go of the accelerate or brake inputs
even when I am still coasting
btw rigidbody should be moved in FixedUpdate not Update
oh?
how is that better?
hmmmm, so it does not matter on the orientation of your car?
nope
because that is the timestep they move on
check google they have many good explenations on the subject
i wonder why it happened for me then
should I move my if statements and stuff to fixed update too?
pretty much anything to do with rigidbodies should be fixed update
i’m trying to make something turn to face the opposite way it’s heading when a function is called.
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(rb.velocity), 1 * Time.deltaTime);
however when called the function does nothing in the scene.
what have i done wrong?
is there a reason you're not using the wheel colliders btw? Unity has a great example of a vehicle on the Wheel collider Docs
I have just never bothered to learn how they work :0
i realise that should make it face the direction of travel not the reverse, i’m going to change that once i get this to do something
https://docs.unity3d.com/ScriptReference/Quaternion.Inverse.html try this function
I put everything that was in the update function into FixedUpdate but now it doesn't move at all. I'm assuming there's something that needs to stay in update? 0_0
that’s the only part of the problem i don’t need yet, for now all i need is to make it actually turn
ur speed too low most likely
transorm.rotate ? are you calling it across frames
So u mean something like that? and do it for all 100 waves?
is this called from update?
the reason i think it is because you are not using local velocity i personally dont see anything that would affect turning other than (unless you are modifying it somewhere else)
if (rb.velocity.z == 0)
{
canTurn = false;
}
this code says if the rb.velocity.z == 0 to not turn but you are using global velocity if that makes sense. and addforce doenst just stop instantly, but if you turn away from rb.velocity.z it will be 0 so im not actually sure whats wrong here other than that
it’s a function outside of start, update etc… being called by a UI button
since that will only move a tiny fraction of a degree
you could be modifying something we are not seeing if thats the case, you should fix that
outside of start / update ? 🤔
do i need to declare the function in start?
no you need this to happen across span of frames
no it needs to be called many many times
you are telling it to move max 1 degree * deltaTime per invok
call it in update()
or a Coroutine
so i need a bool “isDoingThing” and if it’s true then it will execute in a fram?
im guessing its a void
so thats a very small number that you will not even notice
Have a single SO that would have a list of Waves where you'd manage your data in the SO and just reference the SO here.
but each wave will have dif amount of enemies and types of anemies.. example:
sure if thats easier
you need it in update , or coroutine
what is the alternative to that?
are there any significant advantages or disadvantages
would do update if you always got a look target you want it to move to over time
would use a coroutine if its like a 1 off action
like move to this rotation over this many seconds type thing
not really, it doesn't overhsoot, You can also use Quaternion.Slerp (use coroutine for these)
coroutine sounds best, it’d happen reasonably rarely so i think that’s best, welp, off to go learn coroutines
yup that was it 😂
just be mindful these can be called multiple times consecutively(running almost async) by accident and cause unintended behaviors, always use a Coroutine variables or bool to check
yeah it gets strange looking quick if you got multiple coroutines editing the same thing at the same time
one of my first scripts in unity with StartCoroutine in Update 
don't think i made that mistake before, thjough when i was learning unity back in the 3.5 days pretty sure i just used update tick mostly since its what i was used to from other engines
Ahh thats good. I had no coding xp except for modifying some scripts for source engine and some lua for gmod
so many goofy mistakes , who knew Update would be now what I use least, now its mostly coroutines to have more control on the ticks
had some old idtech experience coming into it, and a ton of as2 flash stuff
The data will have to be populated/made somewhere. 100 is quite a bit to be manually configuring from the inspector and hard-coding the data wouldn't be any less messier.
RIP flash
always wanted to use the macromedia software but it looked foreign to me
back in those days it was everywhere
yeah I was a Newgrounds junkie in its early days
like even high school had it a bunch of macromedia stuff installed on all the machines including flash
haha yeah they would block it in my school because they knew people would game on it
yeah not sure why but literally every school machine had flash, dreamworks and fireworks installed
oh thats when the adobe thing happen
what a shitshow lol
I found the problem. I was originally multiplying my turning (horizontal inputs) with my vertical inputs to invert the steering when reversing like a real car behaves. I didn't take into account that when not giving vertical inputs it would be multiplying my steering by 0, therefore not allowing me to steer 🤦♂️ I guess I'll have to find a different way to invert my steering. Probably change a variable based on velocity... idk
yup
if adobe, or autodesk buys something it will be a shit show from then on
Interesting, my brain doesnt work to well at night 😅
Newgrounds was cool, I mainly used it for songs (copyright free of course)
Actually I'm not sure if newgrounds allows copyrighted songs 🤔
same 😭
i’m trying to make an object correct itself after being spun by a collision, how can i detect that rotation so that i can counteract it?
https://docs.unity3d.com/ScriptReference/Rigidbody-rotation.html
also just to be clear, you want to rotate it after the collision has caused it to rotate, or do you mean you want to constantly provide an opposite force to prevent the collision from rotating at all?
yes i want it to rotate after.
in such a way that it appears physically possible that it corrected itself under it’s own thrust
you can use Rigidbody.MoveRotation to do that, you just need the target rotation and the speed you want it to move at. but to get the current rotation you can use that property i linked before
i think the way i want it to happen getting current rotation is better, thanks for the help!
i've been using print to write on the console, i don't use Debug.Log because it's faster to type print. There aren't any differences, right?
print just calls the single parameter overload of Debug.Log. so the only difference is that you can provide more context if you use Debug.Log because it has a few overloads
k thanks
ah i think you misunderstood, i don’t want current rotation as in it’s orientation, i want current rotation as in the speed it is rotating in all 3 axes
yeah that was not clear from what you asked. that would be its angular velocity
sure, not trying to have a go at you or anything, just explaining there was a miscommunication, how would i get that
check the docs
took a solid hour to solve a problem i had, turned out to be a floating point issue, as always 👍
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696