#💻┃code-beginner
1 messages · Page 209 of 1
Gear:
amazn.affiliate/product
gotta offsetem
how?
iono, are you sure its identical to the tutorial?
did you perhaps miss any clicks within the editor it might have made.. etc
the only thing I've changed is the tile images. But they are 36x36, same as video.
I made them in photopea
Does anyone have any pointers on how I can try and fix this
you know what block of code is responsible for all tha?
I would make a bool with Update
for which part. I generally understand yeah
if it's in the range?
i dont get what ur issue is exactly, what is the video showing?
if the mouse is holding down the rubber band and moves away from black it stop following
its hard to tell but basically the slingshot freezes when it exits the range ive set (using max length)
but I want it to start moving again when I go back into the range
if you get it
use a bool then instead of OnMouseDrag which isnt releable
so I thought it would work as im using an if statement within onmousedrag
use Update
just for onmousedrag?
cause i also have onmouseup and down
ya, i would just run two functions in the update, and swap between the two w/ a boolean triggered like nav said
activate bool onmousedown then make bool false onmouse up
if its in range the follows, otherwise no but its still "following"
until you let go
that way, when u go back in range it'll still be updating the position as long as u havent released the mouse
that would mean id also have to move the onmousedown code into the update function right?
yeah i get it thanks
nested ifs 😄
yup.
dont exactly get how I could differentiate the isinrange and held down bool though
how would ishelddown set to true?
ohh okay
i get it now mb
thanks ill try it
if its pressed then u check again if its in range to track.. else dont track
well first of all, how are you setting mouse down
using the onmousedown function
and set to false using onmouseup
what do you mean?
wait hold on nvm
Note that OnMouseUp is called even if the mouse is not over the same Collider as the mouse has been pressed down on. For button-like behavior see: OnMouseUpAsButton.
yeah that'
s the intention
i don't need the mouse to be released on the collider
i think i found the issue
waat? thats a thing?
Yeah who knew right
i juuust got done like hardcoding this kind of behaviour
using a focused object and all that 🤣🤦♂️
lol isnt this basically the Event Trigger?
yea buts its 3d + UI objects
but you can do the same with Event Trigger 😭
ohh was just curious what the benefit was there since they both can raycast on3D cols
like here shortly this walkie talkie should become like a 3d radial menu that also has events they fire off
but i went and tied in the mouse behaviour w/ the selection part of it for now
wait..what was it ?
Nice!
i just have no reason to fire it off yet
im designin for mobile friendly.. so its got me all mixed up w/ inputs
I wasn't getting the mouse position when it exited the range, so it wouldn't know when the mouse re enters the range
i thought coding it out myself would help kinda keep me grounded
well, when u turn that bool on when first click, then u start updating the mousePosition..
it should be updating thruought the period it is or isnt in range
yeah it was supposed to be all in the same update if statement
yeah but i was only getting the mouse pos if it met the range criteria
well do it all the time
if you havent released the mouse yet it should be updating
when u get back into range it should already know the position it needs to go to
yeah i changed it to that and it works now
u dont have to constantly set the position of the sling shot to the mouse position but, u should be updating it anyway since ur actively shooting the slingshot
Am I dumb? Like where is my knockbackValue becoming 0?
Add a debug for the value you are actually sending into the method
That'd mean the value you're passing in is 0 or less
0 * 100 is still 0
are you passing in 0? bc that will result in 0 . . .
10/100 = 0.1 , you probably need to cast to float
Am I forgetting basic math? Isn't 10/100*100= 10?
Is cause it is calculating it as a int?
I though it would try to cast the result to a float, since the method requieres a float
totalDamageTaken / 100f * DamageToKnockBackblahblahblah
totalDamageTaken or 100 need to be a float. the integer division will result in 0 . . .
When you debug in the future, remember to log the entire calculation instead of just one part. No need to assume what the values are, because of cases like this
So... just one of the elements been declared as a float will result on a float as output?
test it yourself
just make totalDamageTaken a float and use Round instead of RoundToInt . . .
is object pooling straight up better than invoke/destroy? are there scenarios where it's not worth?
yes
I think you mean Instantiate
oh yes that
yes, it recycles objects. instantiate/destroy can cause performance issues and gc allocs . . .
cool thx
Yes there are scenarios, but its ultimately up to you to profile to see when you need it. Unless you are spawning objects often you dont really need it. It also makes you add "cleanup code" which is how you reuse the object. You must reset any value that you dont want to stay persistent
Like a rigidbody projectile for example, if you just add it to a pool then now you have to make sure it doesnt have any velocity/torque from a previous usage.
that is exactly what im doing 😵💫
its worth the extra legwork imo
same as writing the physics functions with nonalloc vs the regular ones
I'm making some scriptable objects and was wondering if there was a way to add stuff to the inspector like dividers or sections
attributes sure
[Space(amnt)]
[Header("hi")]
Or a custom editor/inspector.
def for dividers n stuff yeah
This is perfect thanks
Custom inspector may be a bit much, I just want to be able to split the attributes by category
You can find more here, (they're on the left under AddComponent)
https://docs.unity3d.com/ScriptReference/AddComponentMenu.html
if i have a camera and i want it to follow the player but only to rotate on the x axis how would i do that?
Use a ParentConstraint to follow and exclude the other rotation axes
Or better yet use Cinemachine
my mistake i meant a security camera object
i want the x and y to stay the same but it should only rotate on the z axis
Z axis would be roll. That's a weird thing for a security camera to do
the way its setup is a bit odd
but the little half sphere rotates and the camera folllows it
So, I have come pretty far in the last few days.
I have found all the scripts responsible for the firing the:
- Weapon.
- UIManager.
- PlayerManager.
- WeaponSwitcher.
I added comments in the UI manager, Weapon switcher, Weapon, and Player Manager scripts to learn it better.
I organized the UIManager script.
You should make a #1180170818983051344 instead of using this channel as your daily report.
i think this is the right spot to ask this question but anyone know why i have the following error, I have been following a yt tutorial and i cant understand this,,, error CS0246: The type or namespace name 'InventoryItem' could not be found (are you missing a using directive or an assembly reference?)
You have no type InventoryItem
Likely didn't follow the part in the tutorial where they made it.
That's irrelevant. Types are made with code.
this is the script the yt vid had
!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
• Other/None
Your ide is not configured
public GameObject player;
public TextMeshProUGUI coinsText;
private int coinAmount = 0;
private int maxCoins = 7;
// Update is called once per frame
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject == player)
{
Destroy(gameObject);
coinAmount += 1;
coinsText.SetText("Coins:" + coinAmount + "/" + maxCoins);
}
}
So my logic for collecting coins has an obvious bug.
The script is applied to multiple separate coins so the coin amount reverts to 0 every time the script is triggered, meaning that instead of saying "1/7 coins, 2/7 coins, etc.." it says "1/7 coins, 1/7 coins, 1/7 coins"
How do I rewrite this to fix this bug?
The coin amount should be stored elsewhere, not on each coin
isnt this it
yeah coin amount would need to be a player asset
alright thank you
There's more than one step in the configuration steps
Until your IDE underlines errors in red and gives full autocomplete it remains unconfigured
Ngl im in the same boat as him with the IDE, i got the unity package in VS, i set VS in unity, i got VS package installed and updated and still dont got that
the web pages dont say to do anything more so im stumped on it myself, been just using the C# language mode as a substitute
some kind of problem: I've got 8 features each with an increment button to raise its score from a pool of featureXP. Problem being if the total amount of featureXP is enough the increment happens successive times until featureXP is no longer enough to raise a feature's score. Method for comedic effect:
https://i.imgur.com/3rSzXx6.png
Curious if anyone can suggest an edit so that featureXP usage is limited to once per button-mash
!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.
Where are you calling IncreaseAmbition?
On the button its attached to:
https://i.imgur.com/97qgch5.png
// In Player Script
public int coinAmount = 0;
// In Coin Script
private PlayerController playerController;
public GameObject player;
public TextMeshProUGUI coinsText;
private int maxCoins = 7;
void OnCollisionEnter(Collision collision)
{
int coinAmount = playerController.coinAmount;
if (collision.gameObject == player)
{
Destroy(gameObject);
coinAmount += 1;
coinsText.SetText("Coins:" + coinAmount + "/" + maxCoins);
}
}
int coinAmount = playerController.coinAmount - "Object reference not set to instance of an object"
How do I fix this?
...but that's not the issue
the issue is my pool of featureXP is being exhausted instead of stepping the score once
playerController is never set to anything
You need to tell the code what playerController you want to access. Simplest way to do it is check if collision can GetComponent PlayerController
I presume it's attached to your "player" gameobject so just get it off of that in void Start()
playerController = player.GetComponent<PlayerController>();
ooh alr
for some reason VS Code didn't pick up on the error to begin with so I thought it just automatically got it
thanks
never assume anything is automatic in coding, Rhys 
I think the code looks fine? Really seems like it's being called a bunch of times. I'd slap some Debug.Logs around and see where those calls are coming from.
the code looks fine, indeed; but when the solution is running I get an artifact where if I raise a score of 4 it jumps to 6 - it depends on the total amound of featureXP available from character selections
I get the impression its because the if statement encompassing the body of code is technically in effect until rep.featureXP is no longer enough to afford another increment of the score
VSCode didn't pick it up because it's not a syntax error. The error doesn't happen until the code runs
Here is log of error coming while building aab
in hlsl (or for compute shaders in general), I'm having trouble understanding the usage of the X and Y threads
The default code for a compute shader is as follows:
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
// TODO: insert actual code here!
Result[id.xy] = float4(id.x & id.y, (id.x & 15)/15.0, (id.y & 15)/15.0, 0.0);
}
I'm assuming Result is the array for the texture, but why is "id.xy" used?
Most articles online use only the X thread for simplicity but I can't wrap my head around using X and Y
why are you replying to someone in an unrelated conversation 🤔
I have 12 prefabs in my scene that all have the same script attached to them (somewhat irrelevant). I have an event in the script that tells the scene managers and what not that the game is over. but you cannot have a prefab reference something in the scene, whats a good way around this?
The game over event should be on a single object I would think.
Then you can have that single object have a static accessor and access it that way at runtime
See the singleton page here
hey can anyone tell me where is the problem ? I want the box to carry me
more context?
lookup rigidbody platform movement
Do you want to be able to move the box at all?
like its a platformer game and I want to stand on the box while its moving
yess box is in the motion but player cant move the box player can only use it as a platform
like a cart
So no, you don't want the player to move the box
Consider making the box kinematic
no I want the box to move plyer
I understand, but I asked about the opposite
Which is important. If you don't want the player to move the box, don't make the box dynamic
still its having shackky movements and also its not carrying the player when I am standing
it drops the player
Yes, kinematic will help resolve that
Kinematic meaning it does not react to forces (like the players gravity when on top and mass when blocking it)
You can't use velocity though, after changing it
still the sameee
Did you parent the player to the box?
It would be great to see the hierarchy there
nope
might be best to use a parent constraint which you can enable/disable
if you want to move the box and have the player move with it they will need some kind of relationship
having friction wont work?
no
Did you change the movement from velocity for this?
yes
I have attached the code
see
That is using velocity. I asked if you changed it FROM that
can u pls ellaborate 😶 its my first game
Do not use velocity
MovePosition()
what should I replace that with?
cool the movement is fixed now
but the problem of box not carrying the player still remains
keep in mind that parenting will work but the player should also kinematic when on the platform
should I parent it from hierchy or the code???
in the code, then unparent when the player leaves the box
yes
let me try this rq
then you use localposition to move the player
i will write all this in box script right? not the player
no, player script
how exaclty ? 😶
well the player knows when he lands on/gets off the box right?
no I have raycast only yo check if the player is grounded
so you need to add that first
here i just need to add layermask to check if we are on box right?
no you would need to distinguish you're somehow even on the box
if your box has a collider why not use OnCollisionEnter
so just have singleton that is referenced in the prefab's script and when the 'loseEvent' gets called it does an actual event in the scene?
that will detect the collision from sides too not just the top
yes, and then you can raycast down to check if you are on top
ray is best bet ,esp if you want accurate way to detect when off
then how could you make sure its the top?
but you will have to raycast in update instead of on an event
why this simple mech is so confusing lol 😭
i told you earlier too lookup this whole process
you stil need to turn player to kinematic when on platform, otherwise parenting wont keep dynamic from getting twitched off
because computers do not know anything, it is your responsibility to tell them EXACTLY what you want it to do
hey but I still kinda confused why cant I use this raycast with laymasking instead of addding a new one
🤔
no one said you can't you just dont have a Raycast hit param
How would the raycast know you wanted moving platform instead of ground without raycasthit
because you have different outcomes depending on what you have hit, your code will be a mess
sorry if I am asking sm really dumb but I have raycasthit here no? 😶
ur only using to check distance n not what type of collider u hit?
or prob easier to make a another ray that only checks moving plats layer
like this? :O
you can make it the exact same
you still need to check collider with a tag or something
eg
if(raycast.collider.CompareTag("movingplat"))
Apex keep doing what you are doing right now but in future id recommend making a flow chart of how you want your code to run, i made this earlier because i wanted to write a losing method with a countdown for my game.
will keep that in mind thx
correct now? :O
@summer stump Have already used what your solution to my problem was earlier, thanks though i forgot about singletons
interesting low number comparison there
Yeah id assume you could always just do hit.distance != 0f
I have a issue when compiling my game
Do you have everything installed properly?
Sry I accidentally clicked on reply.
😭@rich adder its just making the player big and isnt even carrying the player
Yeah, the screenshot I sent should show everything I have installed
I have a simple compute shader where all it does is assign the X thread id to an int array (basically just incrementing a number)
#pragma kernel CSMain
struct IncrementTest
{
int number;
};
RWStructuredBuffer<IncrementTest> increment;
[numthreads(10,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
IncrementTest num = increment[id.x];
num = id.x;
increment[id.x] = num;
}
I'm guessing the player isn't scaled at 1 or the box isn't.
however I'm getting an error that Kernel at index (0) is invalid
Should probably ask in #archived-shaders or #💥┃post-processing
here's the c# code
private void CubeGrid()
{
IncrementTest[] data = new IncrementTest[100];
int size = sizeof(int);
ComputeBuffer testBuffer = new ComputeBuffer(data.Length, size);
testBuffer.SetData(data);
int kernelID = computeShader.FindKernel("CSMain");
computeShader.SetBuffer(kernelID, "increment", testBuffer);
computeShader.Dispatch(kernelID, data.Length / 10, 1, 1);
testBuffer.GetData(data);
for (int i = 0; i < data.Length; i++)
{
Debug.Log(data[i].number);
}
testBuffer.Dispose();
}
but it's not a shader though
and it's more of a beginner question
It literally is a shader though
Does anyone know what's wrong here? I have everything installed as can see.
Error when compiling is attached as a TXT file
compute shaders are not part of the graphics pipeline
If kernel at index 0 is invalid it means there is an error with your shader code
anyways, I can repost the question in the other channels
HLSL
I dont have a shader?
talking to mookorea mayne
You're probably in the wrong channel. This is the coding channel. Try #💻┃unity-talk for the universal help channel.
Alright thanks
if that's the case, I can't tell what exactly is wrong with the hlsl code
I took a look at those channels, and they're not at all related to my question
ah, I figured out my problem
"num" is a struct, and I was trying to assign id.x (int) to it when I should be assigning it to num.number
Hi, i tried importing a project which my friend made to my computer, i installed his asset folder into mine, but on running the project it gives me some error
the referenced script it is talking about does exist in the folder however
And where does the prefab reside?
hi, i am currently programming a evolution simulation and i have problems with the field of view always outputing angle = 0 even though the direction changes. I have print multiple values and aslo tried Vector3.Angle and inputting vector 2 to vector2.angle or vector 3 to vector2.Angle.
bool IsWithinAngleOfView(Vector2 position)
{
Vector2 direction = position - new Vector2(transform.position.x, transform.position.y);
float angle = Vector2.Angle(direction, transform.forward);
return Mathf.Abs(angle) <= angleOfSight / 2;
}```
This isn't really a coding question but seeing your asset folder structure would be necessary as it's related to your importing of another project.
okay ill send a screenshot of my asset directory
wait i think i sent it before
in the screenshot
this
how did your friend package the project?
steve can u please check my code 🥺
sorry i am not sure what do you mean
he sent a zip file of his asset folder
how do you share a unity project
get him to do it properly. Unity has Export/Import functions in the Assets menu
oh
let me do that
also, will the changes made by me, inflict his code as well
no
what am I checking for?
why is my player not get back to normal it stays child of box even after I leave the box
._.
is there a way to reference all objects that share the same name? Instantiated objects included?
are there any good resources or tools for 2D world generation? I have a good perlin noise function to get a height map which I can use to chose terrain type(biome generation), but I dont know how to populate a tile map with a script based on that perlin noise
for context I am making a game similar in style to factorio, so i am using a tilemap system
A future issue is also world wrapping I would like the game to wrap like sid meier's civilization, and im not sure how to go about that, I believe there are 2 schools of though. either duplicate camera but then objects passing over the border create an interesting challenge, or the load the world in chunks and move one chunk from the other end and then they step on that teleport the player. but this is a future problem I can solve but any useful links would be cool
does anyone know why it results in a null?
because you did not read the Resources.Load documentation
What part of it
if you mean the format of the path, i tried the one in the documentation and it does not work
any versed in conditional if statements? I have a method that increments a score by reducing a featureXP pool, but if the pool is large enough to increment more than once it does so:
https://i.imgur.com/McDWGfr.png
I'm trying to get an increment of 1 per button mash - no more, no less
oops
the whole of the Description
I have sent this question over two days could someone pls answer or did i write not enough infomation?
maybe just tell me what the problem is?
no, read the docs
https://docs.unity3d.com/ScriptReference/Resources.Load.html
hint: read the first paragraph
Spent a lot of time trying to understand why my object wasnt rotating properly....
I was using wrong axys rotation
What does it means? I Have reference to a GameObject that have to on start not active but if I set it into Start() or even into Awake it won't be functional. But if I .SetActive on a button it works normally
Do you have a scene set
omg so much find
Do you mean if player clicks mouse you increment?
And Line 30 is????
The awake function
Awake is called before start
yessir
I'm getting more than singular increments on buttonclick, tho
i literally have no clue lol
what is path even
I used all of it in Start() but it have same problem
Are you using a ui button or using a script?
your Awake function is 3 lines they cannot all be 30
In what order?
so settingsMenuOne is null
both

In this
how many times are you incrementing it?
UI button with script attached
Also, no.1 Dont use gameobject.find
I used public but it had some issue
do you know you can drag and drop the reference?
ofc your field needed to be serialized
Being?
not reference
Did you set them in the inspector?
it's supposed to be once, but if featureXP is enough it will do it two, even three times
I did
Awake is run BEFORE Start, what do you think?
nvm oops
I was doing with start then I just wanted to test it in awake
trying to setActive before you actually Find it ain't gonna work is it?
Take the same screenshot at runtime when the error occurs.
I'll send video
and post your full !code to a paste site
📃 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.
pls someone 😅😭
Position minus position will always be zero
Assuming transform position and position are the same
There's not enough info
you have no variable. Do it as float
Vector2 direction = position - new Vector2(transform.position.x, transform.position.y);
are you sure this is right? kinda looks like it needs to be a Vector2 position, not direction....
And also horizontal have to have H and vertical V
your angle calculation is probably wrong. Use transform.up instead. Assuming transform is something 2D like a sprite, you're probably getting (0, 0, 1) in the forward dir which gets implicitly converted to (0, 0) in Vector2.Angle, and if either of the inputs to Vector2.Angle has a very small magnitude it returns 0
- or Vector2.right, it depends on how you've oriented your sprites. Whatever their forward dir would be
public Rigidbody2D myRigidbody;
public CircleCollider2D myCricleCollider;
public float flapStrength;
public LogicScript logic;
public bool birdIsAlive = true;
public GameObject gameOverScreen;```So, with this stuff, how do you determine what the... I wanted to say "green text", but apparently discords code formatting doesn't colour it like visual studio. Anyway, how do you determine when to use stuff like Rigidbody2D, CircleCollider2D, LogicScript, etc should be. I know they're components on the object, but can you not use the transform properties when you just reference it as a game object?
How can I tell if an object is fully inside a trigger?
One way is to do some math and the origin of the object
I re-created whole scene, same code and it have no problem now. I don't know, I did same things and no problem now
Guys, how can I keep the points saved after I restart a scene
static class or Singleton with DDOL
I tried the DDOL however it doesn't work, I'll send my code 1 sec
{
DontDestroyOnLoad(gameObject);
}```
should it be in a Awake class?
is that a joke?
no
you need to read about the Singleton pattern
can anyone point me in the right direction to achieve something like this? I want loot labels to respect other labels and find a spot on the screen if they are going to overlap
what in the unholy UI that?
no clue'
it looks like they threw 14 games into a blender and poured whatever slurry came out onto their screen
thats what im sayin
It’s path of exile man…. Items on screen are shown in text when you press a button… and there are a lot of items.
Yeah PoE is known for uh… visual excess…
Tbf you generally filter out items by rarity … this is an extreme example…
"mildly extreme"
Anyway they just wanted to know how to have labels show up in screen in a non overlapping manner in relation to screen position of objects they are labeling. I can’t think of a quick and easy way to do this in Unity so I’m sure it’s a custom algorithm they rolled…. I’m not sure this is a “code beginner” question.
tbh this looks like a job for UIToolkit not legacy IMGUI
I feel like you'd do some force directed graph or something
triggers dont work on ui elements do they?
Push the labels away from each other with forces
flex box should handle this situation automatically
i know colliders dont
I'm not quite sure it does, but I've not done something that would managed to be positioned and also moved by layout?
hey, so I added a DDOL on a canvas which keps track of the points however they are duplicating and the points are overlapping, is there a way to remove the one before it
all g @graceful spruce
DDOL on it's own is not enough, you need Singleton AND DDOL
ok I got it now
Ok now I fixed it, but when it gets deleted the white and red score gets deleted to the score is missing how can I make it re attach automatically
This becomes missing
{
private static GameManager instance;
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(transform.gameObject);
}
}
}```
This is attactched to the canvas
presumably that is a scene reference so you would need to do dependency injection on OnSceneLoaded
How to do that? i mean if you could send docs that would be hepful
how can i instantiate a game object, inside of another game object so that the game object im instantiating, dosnt penetrate out of the object im instantiating it inside of, using renderer bounds/extents?
im trying to get the effect of ammuntion and supplies dropping out of a box when it breaks.
i know how to get my object's pivot/origin inside of the box, but that will have the object penetrate the box's mesh, which i dont want.
you really need to learn how to do your own research
and you really need to understand that not everyone has the same knowledge as you in one day
thank you anyway
would have it been so difficult to type 'Unity OnSceneLoaded' into Google?
Hello, so I created a player controller. I want it move and jump on input keys, and it works fine. But after jumping and the player lands on ground the player moves on its own without me pressing any button.
public class PlayerController : MonoBehaviour
{
private float horizontalInput;
private float forwardInput;
public float speed = 10f;
public float jumpForce = 7.5f;
private Rigidbody PlayerRb;
public bool onGround = true;
// Start is called before the first frame update
void Start()
{
PlayerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
if(Input.GetKeyDown(KeyCode.Space) && onGround == true)
{
Vector3 jumpDirection = (Vector3.right*Time.deltaTime*horizontalInput + Vector3.forward*Time.deltaTime*forwardInput).normalized;
PlayerRb.AddForce((Vector3.up + jumpDirection)*jumpForce, ForceMode.Impulse);
onGround = false;
}
if(onGround == true)
{
transform.Translate(Vector3.right*Time.deltaTime*speed*horizontalInput);
transform.Translate(Vector3.forward*Time.deltaTime*speed*forwardInput);
PlayerRb.velocity = Vector3.zero;
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Ground")
{
onGround = true;
}
}
}
I searched "dependency injection on onsceneloaded" as per your request and so much detailed and complex stuff came up
Help, please..
!code
Your problem is you're not logging your code. Get used to using Debug.Log or using breakpoints to figure out your logical problems. If you're still having problems, minimize to where it may be and post again.
📃 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.
public class PlayerController : MonoBehaviour
{
private float horizontalInput;
private float forwardInput;
public float speed = 10f;
public float jumpForce = 7.5f;
private Rigidbody PlayerRb;
public bool onGround = true;
// Start is called before the first frame update
void Start()
{
PlayerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
if(Input.GetKeyDown(KeyCode.Space) && onGround == true)
{
Vector3 jumpDirection = (Vector3.right*Time.deltaTime*horizontalInput + Vector3.forward*Time.deltaTime*forwardInput).normalized;
PlayerRb.AddForce((Vector3.up + jumpDirection)*jumpForce, ForceMode.Impulse);
onGround = false;
}
if(onGround == true)
{
transform.Translate(Vector3.right*Time.deltaTime*speed*horizontalInput);
transform.Translate(Vector3.forward*Time.deltaTime*speed*forwardInput);
PlayerRb.velocity = Vector3.zero;
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Ground")
{
onGround = true;
}
}
}
And this code does what?
did you even read this? #💻┃code-beginner message
Hello, so I created a player controller. I want it move and jump on input keys, and it works fine. But after jumping and the player lands on ground the player moves on its own without me pressing any button.
It's because you're using GetAxis instead of GetAxisRaw.
But also you're mixing Rigidbody motion with Transform motion which is a huge problem
not the question I asked
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerProjectile : MonoBehaviour
{
[SerializeField] private Rigidbody2D MyRigid;
private Vector3 target;
// Start is called before the first frame update
void Start()
{
target=Input.mousePosition;
var heading=target - transform.position;
var distance = heading.magnitude;
var direction = heading / distance;
MyRigid.AddForce(direction, ForceMode2D.Impulse);
}
void OnTriggerEnter2D(Collider2D col)
{
Destroy(gameObject);
}
}```
```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerThrowing : MonoBehaviour
{
[SerializeField] private GameObject MP;
private bool canThrow = true;
void Update()
{
if(Input.GetKeyDown(KeyCode.Mouse1)&&canThrow)
{
Instantiate(MP, transform.position, Quaternion.identity);
canThrow=false;
StartCoroutine(DelayThrowing());
}
}
IEnumerator DelayThrowing()
{
yield return new WaitForSeconds(1.2f);
canThrow=true;
}
}```
Does anyone know why the throwing direction is automatically clamped to throw forward?
The player moves fine before jumping, but when the player lands after jumping the player start to behave strangely. Like it moving on it's own without any input
why dont you debug it first
like debug your inputs
or take a look at your players rb velocity
it could be anything
Thank you, so should I resolve to performing movement using rigidbody only?
this
target=Input.mousePosition;
is a ScreenPosition not a World position
Oh, that very helpful. Thanks!! I'm going to try that.
Still not the answer to the question I asked.
What you should have answered is 'I don't know because I have not debugged anything'
also check if onGround is indeed being set to true, when you fall back to the ground. you might have not tagged your ground gameobject, collisions not being registered and ....
my question is why collision with ground onground true is at the last lines
/\ /\ unanswered question up here for anybody interested
Yes, it is set to true.
set your inspector to debug mode to see private properties, and see if horizontalInput and forwardInput are correct.
it's just method that check if collision is with ground.
So it show that when I land on ground after jumping. The velocity keeps increasing, like every frame. It increases in the direction of jumping(in this case the Z direction)
@agile hornetPlayerRb.velocity = Vector3.zero;
that dosnt look like it is causing their issue. as a matter of fact, i think it should be fixing it
players velocity is set to 0 each fps ground on ground is true
wait what is this?
Vector3 jumpDirection = (Vector3.right*Time.deltaTime*horizontalInput + Vector3.forward*Time.deltaTime*forwardInput).normalized;
dont you just need Vector3.Up to jump upwards? what do all these calculations resault in? why do you need delta time????????? why are you using your forward input to calculate jump direction what is this?
go watch a charachter controller tutorial or something lmao
maybe he doesnt like traditional jumping or smthn idk
yes, I tried to set the velocity to zero there. Now it fixes the velocity issue, but then after player lands, the player now moves upwards in air instead on the ground.
it will jump in the faced direction
wait can I ask you something really stupid
are you sure your scene view is not upside down
Mate, this is used to get the jump the direction. I don't want the player to simply jump up, I want them to jump with some sense of direction.
i nstanitate it just outside the mesh
Yes please 🙂
is scene view upside down or smthng
like the perspective you are watching
or camera idk
if it is..,
i want the object im instantiating to be INSIDE of the box not outside of it
i want it to be completley inside
covered
make the casing not hae a collider
Exactly.
Nope.
yeah bro actually kinda stupid people tell you to go take courses or watch tutorials in these kinds of situations
I see what you tryna do
i kinda like the idea
you are not getting what im saying..... okay look, we have the extents property of two mesh renderers. how do i position the game object of one of the mesh renderers, so it is completely inside the extents, of the other objects mesh renderer
i dk
Well, thanks. I think I should try watching a tutorial.
yooo what about
adding forces
how they gonna do something diffrent if they dont even know how to do it normally...
Creating a playercontroller.
they probably do know'
also i recommend NOT watching brackeys
Creating a PlayerController
id recommend rb based movement
why
is there a way to calculate the angle from the object (transform.up) to the other object where 0 degrees is the transform up, in other words i want to change the world origin point from the angle to the objects one? (I hope you understand it)
pshyics engine be confused with velocity setting to 0 each frame
i dont understand
I dont recommend any youtube tutorials just read docs
it might get a lil hard tho, for a beginner. isnt the built in cc better when you dont need physics interactions with RB's?
The angle between vectors is the angle formed at the intersection of their tails. Learn the formulas to find the angle between two vectors using the dot product and cross product along with their proofs and examples.
how can I prevent this clipping?
i found rb really easy
no yt tutorial
genuinely
Yt tutorials suck
sorting layer
most of them yes
how and what would it do?
A good amount
it wont work good when you tryna have snappy movement, and it will stick to walls, requiring lots of hacky solutions to fix
. any body?
yep. and let me tell you that if its a popular one it suckest the most. 5-10 views is good enough for it to be good
any ideas?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerProjectile : MonoBehaviour
{
[SerializeField] private Rigidbody2D MyRigid;
private Vector3 target;
private Vector3 ScreenPos;
// Start is called before the first frame update
void Start()
{
ScreenPos=Input.mousePosition;
target = Camera.main.ScreenToWorldPoint(ScreenPos);
/*var heading=target - transform.position;
var distance = heading.magnitude;
var direction = heading / distance;*/
MyRigid.AddForce(target, ForceMode2D.Impulse);
}
void OnTriggerEnter2D(Collider2D col)
{
Destroy(gameObject);
}
}```
So this works, but it's just slightly off. Does anyone know ho I could fix it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerThrowing : MonoBehaviour
{
[SerializeField] private GameObject MP;
private bool canThrow = true;
void Update()
{
if(Input.GetKeyDown(KeyCode.Mouse1)&&canThrow)
{
Instantiate(MP, transform.position, Quaternion.identity);
canThrow=false;
StartCoroutine(DelayThrowing());
}
}
IEnumerator DelayThrowing()
{
yield return new WaitForSeconds(1.2f);
canThrow=true;
}
}```
This is where I instantiate the projectile
mess with the instantiate inputs
I'm not understanding your direction
Add force takes a direction not a position
It's just a point here, no?
how can I fix this?
you have been told, sorting layer, if you do not know what this is look at the docs
it will help even considering the object is teleporting to the mouses position?
considering you do not specify what 'this' actually is, how could I know?
this is clipping
sorting layer
wtf is 'this'?
the cannonball is teleporting the mouse and clips into the ground
thx it works
where
here
here
that says this not what this is
replace your forward with up? they are both direction
dk what you mean i sent a vid
still did not specify what this is
what is clipping
which objects are clipping
then wtf did you not say that?
im confused lol
you cannot just say 'this' and expect us to know what this is, you have to be specific
are you confused or is it me
I'm not confused, you need to ask questions better
how is this not enough information
because only you knows what you mean by this
I gave the cannonball and ground the same sorting layer but they still clip
I guess what you really want is to make the ball not go "into" the ground area, i.e. stop at it's surface?
make the ball 1 more
yeah
Then say so for the love of god
okay ill try that
set ball to 1 and ground to 0
does clipping not mean that?
preventing it
Setting the sorting layer will only make it render above the ground
ball just moves over it now
yeah thats what I thought
You could be referring to the camera, background, textures etc
To prevent the ball to actually go into the ground either use colliders and move the ball to the mouse pos using physics or make your own custom stuff
fair
Did you set the correct Order in Layer for both objects?
yyyes
but cause its following the mouse i don't think the layers will change anything?
I think he said the drag operation doesn't use physics until the ball is launched - he's teleporting the ball.
yeah
If you're teleporting the ball directly then nothing besides custom code will prevent it from going into the ground
So either that or physics
but what if I want it so even when the ball is following the mouse, if it touches the ground, it can not go any lower
I know I could use something to do with the y coordinates, but I will have different weapons
Then physics or a bunch of custom code
but what exactly? I don't need the answers given but I don't know where I'd start
Colliders, Rigidbodies
Set the colliders correctly and apply force / change velocity so that it goes towards the mouse
Physics will prevent the ball from going into the ground
ive just been translating it to the mouses position, are you saying it should be translated via physics instead?
do not use translate, use rigidbody moveposition
Or custom code
will the result be visually the same
no
Either that or raycast towards the mouse and stop the ball/string intermediately
when would i do that
whe nthe ball touches?
is there any built in functions which can tell when two objects are touching
like is touching or something
Sure physics
make unvisible colliders?
yeah im gonna try that first
then dont forget collision detection
I recommend clamping by distance or by position as well (or both)
No need for colliders when you can always predict where the object's motion should stop
Colliders don't work smoothly anyway for any non-physically moved objects
yeah theres that
ooh so you are the angry bird guy
I remembr
yeah what spazi and mao says makes more sense in this context
https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html if you need to sync the collider..
Just supporting what Mao suggested ^^
fixed
Just starting to wrap my head around events. I've only used references up to this point. Is there a way to invoke a unity event with a parameter?
i made a player movment script but it has 2 issius
-
if i dont move exactly in one direction (e. g. y=70°) i go faster
-
if i hold down space my second jump is a little bit higher
how do i put my code in a box like this
sure is
@scenic saffronhey man just share it in one of these sites !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.
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
// Your code here
Movment nice
well diagnal movement is usually faster in games because of mathematics
i thought its only when i press to movment keys at the same time like a+w
I worked in 2d games its a common issue in 2ds we used to fix it by claming 1.4 to 1
and normalize in unity I am guessing
for 2nd issue consider a timer
i have a timer
or increaesee cooldown
not working
my first jump is fine then it goes up by a little bit and then it stays at that value
normalize your movement vector before multiplying the speed . . .
I have a canvas where I added a dont destroy on load script, inside the canvas there’s 2 texts and those are assigned to the player 1 and player 2 when object collide with them they lose a point and the other player gets a point. However, when I load another round/scene it says that the text object has been destroyed and im accessing it. How can I fix that?
You'd either need the text object to also be DDOL or for your script to find the new ones when loading a new scene
is there a way to create DDOL object from prefab?
The best way though would be for the text objects to listen to events / read data from your Singleton instead of the other way around
When I add DDOL script to the text it says “cant add them it has to be root game object”
isent it allredy normelized?
Instantiate it, and call DDOL on the instance
I don't see it
movementspeed. ?
yes, it is, but why are you multiplying by movementspeed and 10? also, is this method called in Update, because you're using the default force mode which applies force over time . . .
😮
movementspeed is a float, right? it doesn't have a normalized property . . .
is it movementspeed. ?
my movment vector (moveDirektion) is normelized
when setting a variable does the collider data type accept any kind of collider
yes
it runs in fixed update
trying to make a script where pressing a key will make it so that a cube will spawn in front of player
im using transform.forward and after a lot, ive found that transform.forward vector runs from the origin to the point that is 1 unit from the player head.
(tell me if im wrong)
why doesnt it start from the player head instead of the origin?
If (otherCollider == weaponCollider) --> I am trying to make it so that code only accepts the collider of weaponCollider
transform.forward is the z axis of the GameObject's transform. you need to add how many units in front you want the other GameObject to be . . .
However It does not break despite the reference being correct
then the reference is not correct. Are you using a prefab reference rather than an instance reference
using an instance reference
i guess i will leve the extra speed in the game for speedruners to expliot
but what about the jumping
then log both using GetInstanceID
the transform is located at the pivot of the GameObject. are you using the transform of the player head or the player GameObject?
thanks ill try that
mate i know how to control its magnitude
the problem is that it doesnt exactly give me/convert the local forward point to world space
whats happening is
whenever i try spawning the cube and set its position to transform.forward * 10, the cube spawns 10 units away from origin and in the direction that player is looking
i want it to spawn 10 units away from player and in the direction that player is looking
doesnt matter what the transform im using, even if im using the wrong player object transform
it should still be in front of the player just offsetted wrongly on the y-axis
its spawning from the origin not player
it logs it correctly
nvm it shouldn't be 0 right
well, where are you spawning the cube? we don't know where that is . . .
ur messing with me...
ive told u im tryna spawn it in front of player
lemme just sketch a diagram, it might help u understand
we have no code to look at. i have no idea what variable or value is used to spawn the cube . . .
just forget it, someone else help me
"i have no code to look at"
make it up then mate, ive told u the objective.
lemem just sketch a diagram to clarify
you said you're trying to spawn the cube in front of the player, but where (what position) do you actually spawn it at? show code . . .
can you show me youe script?
why the attitude? good luck then . . .
no it should definitely not be 0
the cube should spawn at (x,y,z)
but its spawning at (x1,y1,z1)
i labelled the x1,y1,z1 as transform.forward cus when i log it thats what it prints
yer 1 sec
/\ /\ unanswered question up here for anybody interested, thanks.
Debug.Log(transform.forward * 2.1f);
Debug.Log(transform.position);
//hum.SetState(Humanoid.States.ATTACKING);
//Vector3 forwardDir = transform.forward - transform.position.normalized;
GameObject clone = Instantiate(cube, transform.forward, Quaternion.Euler(0,0,0));
clone.transform.localScale = new Vector3(1, 1, 1);
clone.transform.position = transform.forward * 20; //tried setting the position so that it would appear in front of player
Destroy(clone, 1);
//irrelevant to the issue but kept it
Collider[] Targets = bc.ReturnTargetsInBox((transform.forward * 2.1f),new Vector3(1,1,1));
Debug.Log(Targets.Length);
@cosmic dagger heres your code to look at'
Yeah transform.forward is a direction, not a position. If you need it to be offset 1 unit forward according to the current position then you need transform.position + transform.forward
dont think he gonna come back. he doesnt even understand the scenario to help me man
isnt it negative? since the position vector is from the origin?
Hey guys, i'm pretty new to coding and idk if this question is more fitting in #⚛️┃physics but i've encountered a weird bug
Basically my Character can move trough walls, but only if i do not see the scene view. What i mean is that, when i have both the scene view and game view open everything is fine and the wall blocks the player. But when i only look at the game view he can suddenly move through them as if they were air
Any help is greatly appreciated
sry was kinda gettin pissed
he never read my original question
my bad
The position is not at the origin
dude i made the same mistake 10 days ago
ty ty
forwardDirFromPlayer = (trans.forward + trans.pos).norm
What?
incorrect
The forward direction is transform.forward, nothing else
incorrect labelling mb
Here you're computing a direction from a position and a direction, that's not right
A direction can only be determined from two positions when doing a subtraction
Your scenario is easy. Spawn at position of the object you want to be in front of, then multiply by how many units away
We can't tell where you're originally spawning the cube without code (that's why I asked)
Now with the actual code, your issue is that you're using transform.forward as the position which is incorrect as that is a direction
Very easy to help and debug but you didn't understand the situation . . .
ye wrongly labelled the variable mb
"Forward Vector from Player"
eh forget it, its working
bad at naming stuff
I don't really know how, but as long as it works
gamedev mindset
they all have colliders, i tried adding rigidbodys to the walls because desperation but that only made it so that i cant control the player outside the bounds for some reason
I also tried implementing code that would snap the player back if he goes out of bounds but that doesn't work either
Hello! I am a new unity designer and I just watched GMTK's beginner flappy bird tutorial. I am trying to make sure that you can't get more score after dying. Please help...
reload scene on death
? I literally started yesterday so i know nothing lol
I cant find much online to help
followm the tutorial
he said the next best thing to do was to try to do this on your own, i couldn't figure it out
you could google how to reload a scene on death
ok
Well i want to keep my game over screen, but if you happen to land in between a pipe, you gain 1 more point.
That's what I want to stop
if you're using cc and not rigidbody, what's the best way to move the character keeping in mind it wants to interact with other objects with physics
is this the right way to set default settings
idk if im doing smt wrong cos its not working
that doesn't make sense
you are trying to load a key
okay nvm i read it wrong
yea it's good
oh ok then its probably smt to do with my code to set the volume from playerprefs
that will ony set it if it already exists. So how do you get the key in the first time?
how would i change this function to target the first enemy it sees rather than the closest?
https://hatebin.com/fgjnpyqqba
pretty sure that's not true
Absolutely sure it is
how do you make a new key in that case?
sorry wrorng, missed the !
are you doing a PlayerPrefs.Save()?
which is now worse because it will only save once
"first" in what regard?
no i somehow never realised that was a thing 😭
it saves automatically on exit
ty adding playerprefs.save fixed it
i have my settings as a different scene as the main menu so it didnt save the playerprefs
you cannot
slow down, give them a chance to explain
i have this script attatched to a tower in my game and it locks onto the nearest enemy and shoots however i would like to change it in a way so that it shoots at the first enemy it sees not the closest
what do you mean by the "first enemy it sees"?
is this like a tower defense game?
so, as I said, you cannot, this code is not suitable for that
yeah similar to how in bloons td the monkeys shoot the first balloon they see and not the closest
if your enemies are in order of first to last just shoot the first one that's in range
no, you need to implement a trigger system, this uses completely different code
steve what are you talking about
FindWithTag gives a random sequence of Enemies not 'the first'
ooh I missed that
good catch
you could make a separate enemy list and append them as they spawn so you can shoot the first one in range
No, you need a trigger system and to implement OnTriggerEnter
but then varying speeds are an issue
they want to shoot the furthest along enemy, how is this achieved with ontriggerenter?
no they want the first in range
the furthest along enemy in range, sorry
usually if you're casting or getting a group of objects in the same frame you'd want to sort it
you could sort by distance along the track if the enemies have a variable for that ^
that would be the best solution I can think of, but I want to know how steve wants to use triggers
simple put a trigger collider on the tower, when ontriggerenter fires that is the one you shoot
that doesn't solve the issue
what if an enemy moves faster inside of the trigger
now it's ahead, but it entered behind another enemy
yes, the first one isn't the first one that enters, it's the closest to the end (at least in bloons?)
roshi, can you clarify
do you want the first enemy that the tower sees (aka the one that enters its range first), or do you want the furthest along enemy the tower sees?
sorry, i should've explained this better, i want to shoot the first enemy but i want the tower behaviour to be similar to how amster is describing it and in bloons
'similar to how in bloons td the monkeys shoot the first balloon they see and not the closest'
yes
so like I said
the furthest along enemy in range
that's how it works in bloons
On trigger enter, add the enemy to a list. On enemy death / on trigger exit, remove it from the list. In Update get the closest one and shoot at it
this also isn't what they want as far as I can tell
oh wait
by "closest" do you mean closest to the goal?
that could work
how do you resolve it all in a list using trigger, ah I guess it wouldn't be on the same frame then
Do like a queue, add newest enemies to it and then fire at the first in queue and check if it's still in range.
sort of
you need to update based on completion to the goal
Ah, right. The course can be somewhat complex too
Little tricky to keep sorted, so I guess you have to go through the list each update.
I guess if the path is not straight you could represent it with a series of nodes, and use something to sort the enemies based on which node they're at, and how much in-between two nodes they are, to get the closest
With a straight path it's simple, but if you make some sort of circuit it gets complex fast
oof can't we just just store a variable for distance to the goal in each enemy
it doesn't actually need to be resolved each frame is there is a cooldown on attacking
should i share my code for reference?
the issue isn't your code
Technically you could only recalculate it when one dies
not inherently
because one could presume some will go faster than others
but if it does need to be resolved each frame, you need to resolve it after physics update (if you're using OnTrigger)
Then do it each frame, and if it gets slow optimize. In order:
- Make it work
- Make it pretty
- Make it fast
or just physics query a overlap sphere or something yourself
Yeah, lot of ways you can optimize it, and I played that balloons game once and it was far from optimized
I'm trying to use my controller, and I can't figure out how to get the axises for my left and right stick. Do I need to change something in my Input Manager's settings
You have scale issue going on
I fixed the things now evrything is going smoothly ty for th help
these videos are the wors
apologies
do a favor and post properly
post !code via website
📃 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.
public void SetMoveNames(List<Move> moves)
{
for (int i = 0; i < moveText.Count; ++i)
{
if (i < moves.Count)
moveText[i].text = moves[i].Base.Name; //Shows pokemon's move instead of the word move
else
moveText[i].text = "-"; // if there is no move it will show -
}
}
no the whole class
also post the error stac trace
also put cs on the same line as ``` when posting code
i did 🤷♂️
this should happen then (int)
cs
not this
ok
but anyway post it through a link
large code should not be posted in codeblocks
https://hatebin.com for example

you supposed to paste it , hit save and send link
are they still trying to figure how to post... 
maybe the code fairy deposited them a working system
the bird
If it fails to save, try another one. A few days ago gdl.space didn't work for another user
why do people omit the rest of the code..
how the hell we gonna know which line is the error if you omit the info
I said post the ENTIRE class
- error from console..
do u mean the entire script?
jesus..
😭
yes, the entire script
the code thats in the file
ok
has the full error message been shared yet?
in a very blury video above yes
it's in the video, but it's just a nullref error
it's not "just a nullref errror"
it's not?
the error contains the filename and line number of the error
the most important parts of the error message
share it
oh sorry yeah
ok now post the screenshot of the error, fully selected in console window
send the error
just send it
ok ok
Code is hard to come by, especially, when they have an error. I had the same issue earlier today . . .
the blury
the full message is never shown in the video AFAICT
Ok so it's this line:
moveText[i].text = moves[i].Base.Name; //Shows pokemon's move instead of the word move1
and it's specifically "moves"
So either moves is null, moveText is null, or moves[i] is null or moves[i].Base is null or moveText[i] is null
Yeah all that could be null
you need to figure out which thing is null first
Not just the text
Debug time
how do i unnull it
is it not telling you in the error?
know which one is null, assign it
You don't do that until you know WHICH is null
don't try to skip the first step
that is only telling us the mfilename/line number/ and method where the error is
that only brings you to the line
there are 5 references on that line that are being dereferenced
wait
can i show u smt
if i comment the line where i call the funciton
look what ahppens
what's your point?
thats when i comment the line when i call the fucniton
to switch the "move" with the pokemons acc move
You still need top fix the error
Debug.Log or attach the debugger
okkkk...
e.g.
if (moves == null) Debug.Log("moves is null");
/// etc```
there are 5 things you need to check
ok
learn to use debugger and step through code 😈
🫡
do while loops check the condition after all the code is ran through inside it or does it check after every line?
Before all the code
it checks before each iteration
thanks!
do ... while checks after, ensuring at least one iteration
while (cond) {
A();
B();
}```
Does:
- check cond (bail out if false)
- run A()
- run B()
- check cond again (bail out if false)
... so on
does for int loop function the same way?
just with incrementation, yes
got it thanks
for loop is:
for (init; cond; increment) {
A();
B();
}```
And it goes like this:
- run init
- check cond
- A();
- B();
- increment
- check cond
... repeat
@abstract finch
note that the init part only runs at the start
it's just a while loop with a couple extra bits
i see thanks!
private static GameController _instance;
public static GameController Instance
{
get
{
if (_instance != null) return _instance;
var gameControllerObject = new GameObject("GameController");
_instance = gameControllerObject.AddComponent<GameController>();
DontDestroyOnLoad(gameControllerObject);
return _instance;
}
}```
I have code on instance object. I already have this object in all scenes. Does it do anything considered GameManager object already exists.
this code is going to create duplicate objects
Yeah as I though gotta remove it
with this code you should NOT have the thing in the scene at edit time
Either use this code OR place the thing in all the scenes
not both
So this is entire thing I need?
Are there any pros of generating such object or no?
Considered on top if you want it to be something more complext then just data storage
Hi, I', trying to create a sequence, where camera flyies through the whole (2d) level, after that the player charachter should play animation, but only after the camera span is over. I've tried it with DoTween and Coroutines, but they still work simultaneously. How to I give full controll to camera first?
Game manager code
private void StartSessoin()
{
// start camera span
playerObserver.StartCameraSpanCoroutine();
// start intro animation
guy.LetGoPresent();
}
CAMERA CODE
public IEnumerator LevelCameraSpan()
{
Vector3 destination = new Vector3(0, yPositions[yPositions.Length - 1], 0);
Vector3 current = new Vector3(0, yPositions[0], 0);
float time = 0;
float timeInterpolator = time / transitionDuration;
while (timeInterpolator < 1)
{
Debug.Log(timeInterpolator);
transform.position = Vector3.Lerp(current, destination, timeInterpolator);
time += Time.deltaTime;
timeInterpolator = time / transitionDuration;
yield return null;
}
yield return new WaitForSeconds(0.5f);
current = new Vector3(0, yPositions[yPositions.Length - 1], 0);
destination = new Vector3(0, yPositions[0], 0);
time = 0;
timeInterpolator = time / transitionDuration;
while (timeInterpolator < 1)
{
transform.position = Vector3.Lerp(current, destination, timeInterpolator);
time += Time.deltaTime;
timeInterpolator = time / transitionDuration;
yield return null;
}
}
📃 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.
I want it to move the camera through the whole level , like a preview of the level, during that fly through no animation should be played, but with the code above camera starts to go up (i have 2d level) and player character starts intro animation in the same time
Simply create a sequence corotouine that does yield return StartCoroutine(CameraSpan) and then calls the player animation
Start coroutine inside another or this should be one big coroutine?
Both can work but I prefer to start coroutines inside a master sequence routine
it worked, thatnks!
i want the camera to rotate how its shown at the start and to follow the player what do i have to change?
use LookAt
You'd need to fix your pivot though
!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.
I have a Singleon class. Is there a good reason not to make all my public methods/members static? So that outside calls can just be "SingletonClass.Function()" as opposed to "SingletonClass.Instance.Function()" ?