#💻┃code-beginner
1 messages · Page 499 of 1
GetKeyDown detects the moment a key gets first pressed
You want GetKey for continuous detection
ohhh okay thank you
But keep in mind that with your current code you'll get a massive speed boost in a matter of a few frames
yeah that just happened, and it just keeps multiplying until infinity
If it's a one-time speed boost only then consider either getting rid of *= and just define a constant sprintSpeed somewhere in your code and assign it rather than multiply it or look into GetKeyDown and GetKeyUp
you want GetGey, not GetKeyDown
yes i have changed that
but how do do that because if i put it like this its invalid
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
sprintSpeed;
}
else
{
speed;
}
Basically:
if (shouldSprint)
currentSpeed = some_sprint_speed;
else
currentSpeed = some_normal_speed;
Yes, because you just wrote down some variable names there, how would the code know what to do with those?
oh I see
So, once again, I suggest taking a C# course, because you seem to be lacking some basics and these are the root of your issues
is it free?
Under Resources, Beginner, Intro to C#
All the pinned resources are free as far as I'm aware
okay i ran into another problem...
if (rb.velocity.x >= 0f)
{
facingRight = true;
}
else
{
facingRight = false;
}
i am trying to make a bool to see of I am facing left or right, which kinda of works
but if i click the left movemnt button it does say im facing left but then when i let go it reverts to facing right
i want it to keep looking left unless i press the right movement key again
i am trying to make a wall check once i make the bool so that if i am running into a wall my velocity on the x axis can no longer go that direction
is it not working because i am using velocity instead of something else
Velocity tells you how fast is the rigidbody in the World Direction. You should choose which direction will be considered as Right. For example, local right (transform.right)? World right (Vector3.right)?
ohhh okay i will try that right now i didnt know that was possible
this doesnt work either though, its saying "cannot implicitly convert type 'unityengine.vector3' to bool"
if (transform.right)
{
facingRight = true;
}
else
{
facingRight = false;
}
my game is 2D i forgot to mention if that matters at all
Search about Dot Product. There should be Vector3.Dot method. Dot gives you a number around 1 and -1.
1 says "you are facing same as that direction"
0 says "you are facing perpendicular to the direction"
-1 says "you are facing opposite of that direction"
oh then cant i use Input.GetAxisRaw("Horizontal") for that?
This is wrong. An "if" block will need a boolean. For example: is it bigger than zero?
But you are checking nothing at all. You should take a C# tutorial.
What GetAxisRaw("Horizontal") does? It gets a horizontal vector or int (if i remember correctly).
Lets say that method gave you an integer "1".
If you do this:
if (1)
It will mean nothing. Compiler will tell you exactly that.
i accidentally click f10 while scripting and it did something
But if you do that:
if (1 < 3)
Then it will be valid.
That means:
if (Input.GetAxisRaw("Horizontal") < 3)
oh i thought it makes it so if you click your right key it gives a value of 1 and if you click your left key it gives a value of -1 and when you click nothing it has a value of 0
i have this button, even if i click it nothing happens
the code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneManagerScript : MonoBehaviour
{
public void LoadScene(string SceneName)
{
SceneManager.LoadScene(SceneName);
}
}```
the onlick event seems right to me
also the build settings
@queen adder i was able to solve my problem
i made a string variable "lastDirection" and used GetKeyDown to determine if my "facingRight" bool is true or false
so if my velocity.x was equal to 0 (meaning im pressing nothing) that my bool = lastDirection =="right"
heres the code:
private string lastDirection;
void Start()
{
lastDirection = "right";
}
void Update()
{
if (Input.GetKeyDown(KeyCode.D))
{
facingRight = true;
lastDirection = "right";
}
else if (Input.GetKeyDown(KeyCode.A))
{
facingRight = false;
lastDirection = "left";
}
else
{
if (rb.velocity.x == 0)
{
facingRight = lastDirection == "right";
}
}
}
i have a question: is there a better way to generate Random.InUnitSphere or OnUnitSphere within a parallel.for or parallel.foreach loop
because they usually return that they can only be run on the main thread
You can use System.Random to generate those random positions and make one Random instance per thread for example. System.Random doesn't have those methods built-in so you would have to generate couple floating point numbers and combine them into those coordinates. You can search up for some resources online as to how to do that
Okay I think I'm making progress on this rock spawning thing.
https://hastebin.com/share/irolitiyop.java
Everything is working fine, except that my height check is kinda messed up and I don't understand why.
In the code, maxYPosition is set to 3, and minYPosition is set to 1, so I'm not really understanding why my rocks are spawning below 0 on the y. 😕
Can anyone see my mistake please? Been staring at it for too long. lol.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Thanks alot
This seems really good example of couple of ways to get points in sphere https://karthikkaranth.me/blog/generating-random-points-in-a-sphere/. Normalizing the coordinate will give point on sphere, you might wanna take into account the possibility of the point being (0,0,0) in which case normalizing is not possible.
You could code the normalization by yourself and when length = 0, return (0,0,1) (almost inpossible to happen so shouldn't affect the overall distribution) or pick new coordinate. Unitys normalize method returns Vector3.zero for zero length inputs which might cause issues depending on your case
thank you so much
ive been working on this fluid simulation, looking at the papers i applied the equations, but when two particles got in the same position they combined so i needed a random pressure force to push them away
instead of just returning zero
Strange that unity does not provide build in SpherePoint struct for operating on polar coords, they can be really handy. Or does it? Anyways making such struct yourself is quite easy
This may be of help (probably already seen it, but still. :))
Let's try to convince a bunch of particles to behave (at least somewhat) like water.
Written in C# and HLSL, and running inside the Unity engine.
Source code:
https://github.com/SebLague/Fluid-Sim
If you'd like to support me in creating more videos like this, you can do so here:
https://www.patreon.com/SebastianLague
https://ko-fi.com/sebastia...
I am making a script to flip my character depending on which direction im facing, I have a working system to check which direction im walking, but my player only flips if I click A instead of A and D, if i click D my player doesnt flip but just moves with the player facing whatever way A set it to can someone please help
you need to provide code for someone to help you
if (Input.GetKeyDown(KeyCode.D))
{
facingRight = true;
lastDirection = "right";
Flip();
}
else if (Input.GetKeyDown(KeyCode.A))
{
facingRight = false;
lastDirection = "left";
Flip();
}
else
{
if (rb.velocity.x == 0)
{
facingRight = lastDirection == "right";
}
}
}
private void Flip()
{
if (facingRight)
{
transform.localScale = new Vector2(transform.localScale.x, transform.localScale.y);
}
else if (facingRight == false)
{
{
transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}
}
}
}
there is the code, sorry
there are 0 warnings and 0 messages, so the code is technically correct, but my player doesnt flip when I click D
also you can try swapping A with D behavior and see in the inspector if scale is set to negative, didnt do much 2D, but negative scale can mess things up in 3D, so maybe 🤷
Sorry my answer was all over the place. lol. Gimme a sec.
well i kinda fixed it so now it flips if i click A or D, but I still have same problem but both keys do it now
You should be able to modify this to fit. I use this snippet to switch between firing left gun and right gun.
if (leftLastFired == true)
{
Instantiate(bulletPink, firingPointRight.position, firingPointRight.rotation);
StartCoroutine(MuzzleFlashLight(leftLastFired));
leftLastFired = false;
}
else
{
Instantiate(bulletPink, firingPointLeft.position, firingPointLeft.rotation);
StartCoroutine(MuzzleFlashLight(leftLastFired));
leftLastFired = true;
}
Not sure how it works with 2d though tbh.
I already tried changing it to work with the "lastDirection" string, it still does the same thing
do you thinkit would work if I do something like this:
if(rb.velocity.x > 0)
{
Flip()
}
i just tested it it doesnt do that but I still have the same problem
Debug your bool and your localscale.x (or serialize them)
also your Flip() method is named improperly i think. Flip is to... well flip. No matter which direction. So it should be just
void Flip(){
transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}
thats how it is
Actually yeah, that above will just invert the current local scale, so you don't even need the bool.
but if there is no bool, then how will it know which direction I am facing
do it outside the flip, check if direction changed, if it changed - do Flip(), otherwise dont
im about to test it with out the private void, is that what you mean?
it doesnt matter
yeah I just tested it, I thought this would happen, but my player now flips over and over no matter what
what i mean is:
string lastDirection = "right";
void Update()
{
string newDirection;
if(Input.GetKeyDown(KeyCode.A){ newDirection = "left";}
else if(Input.GetKeyDown(KeyCode.D){ newDirection = "right";
}
else {newDirection = lastDirection;}
if(newDirection != lastDirection) {Flip();}
lastDirection = newDirection;
}
void Flip(){
transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}
probably it could be done better, but at least it is readable imo
let me try it
(#edit - added semicolons)
Add debug logs to print new direction and last direction when the key is pressed
Also debug.log "flipping" in flip method, basically debug log is your friend when anything does not work as expected
Also you can get rid of else statement, and set string string newDirection = lastDirection on the first line of Update, but this will probably not change anything, just make code cleaner
Where can I ask about colliders?
Assuming you aren't changing the scale of x elsewhere:cs private float localScaleX; private void Start() { localScaleX = transform.localScale.x; } private void Update() { var localScale = transform.localScale; if(Input.GetKeyDown(KeyCode.A) localScale.x = -localScaleX; else if(Input.GetKeyDown(KeyCode.D) localScale.x = localScaleX; else return; transform.localScale = localScale; }
Wasn't my question. 🙂
Ah replied to the wrong post.
i found a different solution following this yt vid if you want to check it out https://www.youtube.com/watch?v=Cr-j7EoM8bg
Hi everyone! 🙂 Today I will show how to flip your 2D character in Unity.
Learn C# here: https://www.youtube.com/watch?v=HB1aPYPPJ24&list=PL0eyrZgxdwhxD9HhtpuZV22KxEJAZ55X-&ab_channel=DaniKrossing
Download Unity here: https://unity3d.com/get-unity/download
➤ TIMESTAMPS
00:00:00 - Intro
00:01:01 - My player script so far
00:01:48 - Method 1: Fl...
go to 3:40 to see the method
the problem with my code before, is that the bool wasnt being used to detect if I was actually fdacing left or right, therefore I could flip infinitely
also im sorry if I am not allowed to put links
is that allowed?
@sand snow i can see 5 hours of questions from you. Maybe make a thread
i got the solution
sorry about that ill try to start remembering, please forgive me if I forget
umm any1 can give me a direction to how do I create a level system for an rpg game?
very broad statement
do you have any plans on what your levelling system is like?
1v1 turn based combat system
What will the player do to level up?
What will the player gain from levelling up?
What will be displayed when the player levels up?
Do think of more questions you can break down before making this
What will the player do to level up? defeat enemies
What will the player gain from levelling up? his stats like dmg, defence, health ect will level up
What will be displayed when the player levels up? just like standard level up messege with maybe some infomation on what happened
I mean I'm not looking for something too complicated just like asking if I need a seperate maneger for it or do I need to do it in the players script
ok and what do I do there? do I not put any information about the levels in the player's script?
for example the current exp max exp level ect?
Nah
To be honest it's up to you
ye ik but like im just asking for the better way to do it
But I prefer to have one responsibility per class, like player combat and player movement has its own scripts
im tryna enable the moving speed under my script
So ideally you keep your RPG levelling in it's own script too
ok tnx
how would i go about making dash because evrytime i try it only dashes the one way no matter the way my sprite is facing
https://paste.ofcode.org/DnqEpRUxQZGhGxAjbARy4w
double check line 17 and 18
ok
Configure !ide to highlight typos
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
which part of the script handles the moving of the player due to dashing?
i removed the bit that dashes cuz i tried a lot and none worked so i was just goiunbg to redo it from the ground up
youll need to get the side that the player is facing. you already have a isFacingRight bool which you can use here
can someone help me out here, the enemy ai movement is with navmesh. Why when it start to attack the player, the circle goes past the player circle
whats the issue with the code???
In addition to your error, you should not multiply mouse input with deltatime
Here is a code
[SerializeField]TextMeshProGUI textdisplay
public void buttontap()
{
if (val== "=")
{
double e=System.Data.Convert.ToDouble(System.Data.DataTable().Compute(CurInput,"");
CurInput += val;
textdisplay = CurInput;
}
}
public void Update()
{
public string CurInput="";
string val="4+15+63";
}
and when i press the button, it displays CurInput as NULL string, not updating itself. Although, it is updated when i press twice, but the error is still displayed:- "Cannot assign double values to DBNull"
No way to answer that if you dont show your code
its all under a class
-
- You multiply after a semicolon. This is a beginner syntax mistake
-
- No
deltaTimeneeded, since it's already included inGetAxis
- No
-
- Make a
Vector3out of it
- Make a
in original code, I am using length function to CurInput
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Data.Common;
using System.Data;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
namespace TheProj
{
public class Clac : MonoBehaviour
{
public TextMeshProUGUI disptext;
private string CurInput="";
private double answer;
public void ButtonTap(string val)
{
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
int s=CurInput.Length;
Debug.Log(s);
CurInput += val;
Debug.Log(CurInput);
UpdateDisplay();
}
}
public void ans()
{
answer = System.Convert.ToDouble(new DataTable().Compute(CurInput, ""));
CurInput = answer.ToString();
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}
}
is tghis the best way i could do this?
Please, use sites to paste your code
!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.
The best way would be to add else to the 2nd if, since there is no need to check for the button release if it's pressed this frame
pasteofcode
so theres no syntax like keyheld?
How i start editing the script i back delete and its now working i litterally install jetbrain for external tool
!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.
spent 2 days on this one issue now
If the key is being held, GetKey is used. Other syntaxes are provided by the new input system and EventSystem. The latter one should be avoided in non-editor scripts
im kinda new to git when i set up a repository with unity how do i set up a git ignore to ignore the library folder
Since you call the method on a nullable DataTable
Include the git ignore for Unity when creating a repository in git hub
yesterday when i was on here, someone told me to check curinput as debug.log and it was inputting empty whenever i pressed any number or operation for the first time
howd u do that
Not sure what this means
even after i put it twice, which for some reason made the string as 1+2(I click 11++22)
Create a repository in git hub and check "include git ignore". Select it for Unity
It wont like me type
the error persisted
It doesn't let you type?
fix? saw this on a tutorial
ditto code
no
nvm bro i fix it
Use this bot's instuctions for posting code #💻┃code-beginner message
What is the answer variable supposed to be assigned to?
CurInput, string
CurInput=answer.ToString()
with a ;
how would i go about getting the enemys transform and moving it towards the player when it triggers this boxcoillider2d
https://paste.ofcode.org/za9FkjZCdrWmfTLSuVr6KT
What is the method ans supposed to do?
calculate the value? its a void with answer
The collisions logic should be controlled in the Enemy script
What do you use the Compute method for?
computing mathematics
ive never used compute but it takes string such as 4+3+15 and computes it and gives the answer back in double, which is then changed into CurInput string
currently how i have the proccess is
if left mouse is cliked > set the boxcolldiers agme object to true > then if the collide on said game object makes contact with enemy > i want to access the enemy transform
all in one scripot
and you wnat me to do iyt multiple scripts right?
It is supposed to compute the column. You only have CurInput, which is, supposedly, an expression?
DataTable table = new DataTable();
table.Columns.Add("Numbers", typeof(int));
table.Rows.Add(10);
table.Rows.Add(20);
table.Rows.Add(30);
object numbersSum = table.Compute("SUM(Numbers)", string.Empty);
// 10 + 20 + 30 -> 60
The following example calculates the sum of the rows in the Numbers column with string.Empty filter, meaning that all numbers are included
| Numbers |
| ------- |
| 10 |
| 20 |
| 30 |
Yes, it is much better to create an additional script for Enemy
anyone knows how to fix this?
i can't seem to know how to reproduce it but it happens often out of no where
Reattaching to Unity fixes the issue for me
How exactly?
I don't start my game from unity ever
I always do Attach to unity and play
I use Attack to Unity. I think this happens when first enabling debugging and starting the game while it's still being configured
i downloaded cinemachine install right but i don't see it as a tab its suppose to be beside component how do i fix it?
Not a code question, but
Okay guys so I have a scene with a play button and when I click the play button it takes me to my second scene as intended but it only lets me view the scene like this instead of letting me be the player can anyone tell me why?
Does that player have a camera? Do you have another camera in the scene?
yea forgot to add camera to player xD
my bad
I dont know what happened to all my things i had working
I was messing with the button screen and everythign went away on my other scene
Hey guys I'm making a dungeon like room generator, it's just hallways and stuff. I need to do occlusion of course for this because it's huge, but normal occlusion doesn't seem to work at runtime. Is there any way I can get help with this, it's the most important part of my game.
Problem is it's 8 years outdated.
Or program some sort of "portal-based occlusion" yourself
Which I think would be the simplest way to implement it
Thing is it could be a really long hallway then some get cut off
Long hallway made out of multiple rooms
That's not an issue if you implement it correctly
This is weird, does it look like it's working?
It just started doing this
It seems to be only FOV though.
Biggest problem is it cannot be an occluder
Yeah I don't think that the built in occlusion is suitable for procedural stuff
I'm in the middle of writing my own occlusion system for generated areas. If you find something useful please ping me though @shy ruin
Ok, what should I do right now though.
Did you try it?
Fine, I'll try it but the reviews say there's a ton of deprecated variables.
Fixing those would likely be easier than writing your own from scratch. I havent' found any alternatives yet
@shy ruin There's also a new GPU occlusion system apparently: https://docs.unity3d.com/6000.0/Documentation/Manual/urp/gpu-culling.html
Maybe it will work for runtime generated stuff
Unity 6.0, I'm not using it
in visual studio it sometimes gets the references and has the autofill, but now i opened a second new script and it doesn't detect any of the unity systems. not even debug.log();
does anybody know what can cause this?
so far there are 2 scripts in this project. 1 works fine, the other doesn't.
Instance OC is completely broken, doesn't work.
The only thing left is your portal method, any way you could point me in the direction to understand it and get working on it?
Maybe this series https://www.youtube.com/watch?v=8xgb-ZcZV9s&ab_channel=thebennybox
It's some pretty advanced stuff though, definitely not a beginner subject
@shy ruin Looking at the video series I linked it seems really complex, even for me (going into SIMD stuff etc.)
But keep searching for solutions, especially portal-based, since that should work the best for closed spaces like dungeons
Here, I have an idea. Loop through each room, (200+), and use the camera frustum culling method to check if it's within view. If it is then show it, if not don't show it?
Using cameras and custom shaders is a possibility yeah. There might be some big issues I can't think of right now
I'll try it, it shouldn't be too hard.
Btw frustum culling doesn't really help you here. An area can be in the frustum but still be occluded by a wall
I'd probably render the camera to a rendertexture with certain colors representing certain areas. Then use a script or a compute shader to check if an area's color is visible in the texture
That's why I'll linecast to ONLY visible points, which only will be like 20, and check if it's visible from the raycast
for some reason I keep on getting this error, everything runs ok but I still get this for some reason
It's an editor bug
editor bug, close any graph tabs you have open
hi! im making a 2d maze game in Unity for my comp sci coursework and its been working fine so far, however, after i created the playerEnemyCollision script for my game and ran the program, a few errors came up.
- the hearts/lives disappear from the screen (i added this as a sprite rather than ui)
- when i dont move the player, the enemy characters move/push the player outside the screen on its own
- in the console, it does not report "Game over" when the enemy and player collide.
here is my PlayerEnemyCollision script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.transform.tag == "Enemy")
{
Debug.Log("Game Over");
}
}
}
here is my lives manager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LivesManager : MonoBehaviour
{
public static int lives = 3;
public SpriteRenderer[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
private void Awake()
{
lives = 3;
}
// Update is called once per frame
void Update()
{
foreach(SpriteRenderer heart in hearts)
{
heart.sprite = emptyHeart;
}
for (int i = 0; i < lives; i++)
{
hearts[i].sprite = fullHeart;
}
}
}
!code. Use 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.
how can i check if the event has anything inside of it?
before calling it
which one would i use
this works
hi i have a quick question i have N items and i want to store them
actually i'm making a big Dictionary where i have
Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<int, Dictionary<int, Dictionary<string,>>>>>>
where each dictionary take a specific value :
DisplayName
ID
CustomData (json file)
Quantity
Price
Currency
can i do it easier ? i'm actually stuck with this format
what on earth are you trying to achieve, this looks like a job for an RDBMS
At a minimum make a struct or class with those fields and put them in an array or maybe in one dictionary with id as the key
Make a class that has all of those fields, then a single dictionary from string to that
hi stupid question, is there an offset to the mouse vector3? Like my Input.Mouseposition is so far from my original screen (while the screen being at 0.0.0)
private void OnMouseDrag()
{
mousePos = Input.mousePosition;
this.transform.position = mousePos;
}``` i tried something super simple
you need to use ScreenToWorldPoint to convert it
Thank you, thought so i was missing something
https://gdl.space/saquketina.cs hey can somebody explain to me why i get a NullReferenceException on line 62?
what would you expect?
CurrentlyGrabbed = null;
if (CurrentlyGrabbed
how can you compare a tag on a null object?
ohh, thats why in debug.log it was taking
1
+
3
oh that makes sense ty
does it work if i put the CurrentlyGrabbed = null; behind the if statement?
also who the actual f did you make the colors there
yes, it would work if you set it to null after the if because it is no longer used.
colours come from properly posting inline !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.
if(Currently = null)
yoo thats cool ty
fyi, should be ==
yeah youre right
Hey, I made a basic cc (rigidbody), and for some reason it seems to be very choppy, you can see the tree in the left, and every child and parent is on scale 1 and the camera is a child of an empty which updates to the position of an empty on the player called cameraPos. Help is appreciated.
public class TriggerFix : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
Debug.Log("Touched collider: " + other.name);
}
}```
I have an object that has a collider set as a trigger with a script that checks for OnTriggerEnter, which works, however if any other trigger is being activated, it executes this too
How can I restrict this OnTriggerEnter to that one BoxCollider?
Thought it might cause some lag
Why would it do that?
public class PlayerMovement : MonoBehaviour
{
// General variables
public float movementSpeed;
public float groundDrag;
// Collision and jumping
bool isOnWalkableGround = false;
public float playerHeight;
public LayerMask ground;
// Movement variables
float forwardInput = 0f;
float horizontalInput = 0f;
Vector3 moveDirection;
Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
void Update() {
// Ground check
isOnWalkableGround = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, ground);
UpdateInput();
ControlVelocity();
// Drag
if (isOnWalkableGround) {
rb.drag = groundDrag;
} else {
rb.drag = 0f;
}
}
void FixedUpdate() {
MovePlayer();
}
private void UpdateInput() {
forwardInput = Input.GetAxisRaw("Vertical");
horizontalInput = Input.GetAxisRaw("Horizontal");
}
private void MovePlayer() {
moveDirection = transform.forward * forwardInput + transform.right * horizontalInput;
rb.AddForce(moveDirection.normalized * movementSpeed * 10f);
}
private void ControlVelocity() {
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
if (flatVel.magnitude >= movementSpeed) {
Vector3 factoredVel = flatVel.normalized * movementSpeed;
rb.velocity = new Vector3(factoredVel.x, rb.velocity.y, factoredVel.z);
}
}
}
This doesn't have the code that moves the camera. But I suggest you just make the camera a child of the player if the only reason it's not already there is to avoid lag
Alright, thanks
It didn't fix the issue. By the way, the stuttering only happens when I move my camera and move at the same time. It also happens but only a little bit when moving only the camera, so moving might just be amplifying it.
So here's the camera movement script:
public class CameraHandler : MonoBehaviour
{
public float xSensitivity;
public float ySensitivity;
public Transform playerTransform;
float xRotation;
float yRotation;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * xSensitivity;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * ySensitivity;
xRotation -= mouseY;
xRotation = Math.Clamp(xRotation, -90f, 90f);
yRotation += mouseX;
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
playerTransform.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
Hopefully it clears it up in any way
Maybe use a Tag?
On the trigger? If yes, how would I check which one fired
The OnTriggerEnter has a collider parameter, I think it has a tag property.
Yeah, and I can check what has collided with the trigger, however the other collider isn't the issue
Currently any trigger I touch with the other collider calls the event, somehow
is haset only used to avoid duplicates or it has any other use?
Are you sure the other one doesn't have the script? That's weird.
Yep, other ones have their own scripts
show the code where you calling the event
Can anyone please help? @keen dew ? Why does it stutter?
use layermask
Could you tell me a bit more or direct to an article about it?
Managed to solve most of it, nvm.
When I open this prefab in the prefab editor it shows like this (just white blank image)
but in my game or in the editor, it looks fine
why?
width = 0 , height = 0
that's the container which is an empty object
no you're actually right lol
why does it reset in prefab editor though?
could be alot of reasons
try using lateUpdate instead of Update
- Don't multiply mouse input with deltatime
- Don't modify a rigidbody object with transform, use the rigidbody instead
Is there a way to create a vector instance with magnitude and angle?
I mean I know I can implement it but before I do I wanna know if there already is a way
Whats the difference?
In 3D?
2d vector in my case
You can use Mathf.Sin and Mathf.Cos and then multiply the vector with the magnitude
Oh and Mathf.Deg2Rad assuming you want to use degrees not radians
Or ditch the trigonometry and do Quaternion.Euler(0, 0, angle) * new Vector2(0, magnitude)
Isn't this for including/excluding colliders? The issue is not that the wrong collider calls the event, but that in area, where are multiple triggers and there is 1 with this script, although if the collider enters any trigger (no matter if the trigger has or not the script) the event gets called
Ex. Trigger1 with the script, Trigger2 without the script
If collider named "player" enters Trigger1, the event gets called, but somehow, if the same collider enters Trigger2, the same event gets called, even though the Trigger2 doesn't have the said script
then you can check if the other collider has the script before calling an event
Then how can I make sure experience doesnt change depending on framerate?
The other collider doesn't have the script, the trigger one does
Mouse input is already framerate independent
Otherwise it would be pretty easy to fix
* Time.deltaTime makes it inconsistent.
Oh, good to know
I wish those youtube tutorial makers also knew...
yes but your code is checking if you detect any collider debug this
is there a way to trigger functions in the animation timeline
Wdym? That's right, it checks if any collider enters the trigger, however once again the issue lies in the fact that somehow when entering other triggers it gets called too
thanks
is there a reason why my animation is only triggering once through code
{
m_RB.linearVelocity = Vector2.zero;
m_RB.constraints = RigidbodyConstraints2D.FreezePosition;
m_Anim.Play("SlamAnim");
//m_RB.AddForce(Vector2.down * m_SlamStrength, ForceMode2D.Impulse);
}```
public List<RaycastHit> sortedHits;
// In update for example
sortedHits.Clear();
its giving me an error on the sortedHits.Clear();
RaycastHit is not serializable in the inspector
so List is never put in the inspector, therefore is never initialized by Unity
i dont need it in the inspector
with that said you need to initialize it yourself
the list is null because its not initialized
private List<RaycastHit> sortedHits = new List<RaycastHit>();
correct
How to convert color to HEX please
cuz i've strucks this error
holy flashbang
It's X not x
No X lead to the same mistake
or use the RBG variant if you dont want to store alpha
thanks that works
goodmorningyall, wee are about to work on some more building mechanics! lol
using System.Collections.Generic;
using UnityEngine;
public class Building : MonoBehaviour
{
// Variables
private GameObject playerObject;
private GameObject cameraObject;
private KeyCode buildToggleKey = KeyCode.B;
private int buildKey = 1;
private int destroyKey = 0;
[SerializeField]
private bool buildMode;
void Start(){
playerObject = GameObject.Find("Player");
cameraObject = GameObject.Find("PlayerCamera");
buildMode = false;
}
void Update(){
// Toggling build mode.
if (!buildMode && Input.GetKeyDown(buildToggleKey)){
buildMode = true;
}
// Methods that occur during building.
else if (buildMode){
if (Input.GetKeyDown(buildToggleKey)){
buildMode = false;
}
// Build.
if (Input.GetMouseButtonDown(buildKey)){
build();
}
// Destroy.
if (Input.GetMouseButtonDown(destroyKey)){
destroy();
}
}
}
void build(){
Vector3 buildPos = transform.TransformPoint(cameraObject.transform.forward * 3);
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
// Transform the coordinates of local space to world space.
cube.transform.position = new Vector3(Mathf.Floor(buildPos.x), Mathf.Ceil(buildPos.y), Mathf.Floor(buildPos.z));
}
void destroy(){
}
}
```How do yall think I should go about making a block that outlines the block I am about to place in my building programming.
For completeness, it doesn't work because rgb on Color are floats. They cannot be formatted with "x".
Use Color32 which uses bytes if you want to make the conversion manually.
Format string x yields hex in lowercase, X uppercase.
Should I make it create a transparent object in every valid space the player can place a block, and delete the object everytime they move, or should I do some sortof shader programming?
oh right x is lowercase 
Also I know my logic for placing blocks isn't the best at the moment, I just wanted something functional xD
i have a weapon switch mechanic and after a number of switches my sword rotated and stays in that position, any fixes?
Yes
how?
Do you honestly think anyone can answer that without seeing your code and other details 🤔
yeah sorry bro 😅
can anyone explain to me why am i getting a null refrence error when the level system is crealy assinged to the player GO along with the scripts
Vector3 buildPos = transform.TransformPoint(cameraObject.transform.forward * 3);
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
// Transform the coordinates of local space to world space.
cube.transform.position = new Vector3(Mathf.Floor(buildPos.x), Mathf.Ceil(buildPos.y), Mathf.Floor(buildPos.z));
}``` Okay quick question, How can I make this block transparent, I saw some tutorial of a dude creating a stencil
You should not use constructors with UnityEngine.Object classes such as MonoBehaviour
Use Awake/Start for initialization instead
is it possible to make your own attribute which would expose the variable in the editor
but make it read only?
so you couldnt assign anything by dragging or clicking
you would only be able to assign it through script
If you using something like NaughtyAttributes it has a ReadOnly attribute for that
whats that
an asset?
It's a free asset, yes
using NaughtAttributes if you only need Readonly is a bit overkill
iirc someone had a script that just made that 1 specific attribute
i just wanted to see what it offers
I did it in the start method but a wierd thing happend, it worked but I still got the null refrence method
oh sure go for it, it has many things
was just saying, if only need the ReadOnly attribute, is also fairly easy to make
even though the unitLevel did got the value of the playerLevel
yeah
im gonna give it a go
send screenshot of your levelmanager object
inspector
Get rid of the constructor completely.
Make sure that levelManager.playerLevel is assigned before this Start method runs.
Make sure you don't have extra instances of this script in the scene
dont I have to have a constructor because I need to inheriet the variables of Unit class?
did it
Idk how those things are related but, no you should never use constructors on monobehaviours
this is gonna be so useful
nice except for the camel case publics 😛
the null is im assuming is playerLevel , so even tho its assigned its still being given a null value
levelManager.playerLevel;
^ this is probably whats null
not null just debugged it
and I got rid of the constructor and I still get the null refrence
even though it works...
thats wierd
Did you read the last line in this message?^
Type t:playerscript in the scene view search
pretty sure its all assinged unless I missed something
nevermind
found my mistake
What was it
I did not assinged it to the enemy game object
thats because the level system is for the player only
and I didn't think about it but I shouldn't have created the refrence to the levelSystem in the unit class
but in the player class only so ill fix that
Vector3 buildPos = transform.TransformPoint(cameraObject.transform.forward * 3);
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Material transparentMaterial = "Assets/Materials/TransparentBuildingMaterial";
MeshRenderer cubeMesh = cube.GetComponent<MeshRenderer>();
cubeMesh.material = transparentMaterial;
// Transform the coordinates of local space to world space.
cube.transform.position = new Vector3(Mathf.Floor(buildPos.x), Mathf.Ceil(buildPos.y), Mathf.Floor(buildPos.z));
}``` I'm attempting to load my material and apply it to this cube, what is a way that I can do this
uh at minimum use Resource.Load
or better use a reference in inspector
I tried resource load, but it said to place that in an awake event or something?
instead of .material you should target the .sharedMaterial when possible
sure you can place it anywhere
If you are experienced developer, use addressables. You should learn what is an addressable is
private Material myMat
awake()
myMat = Resources.Load("someMaterial")
Alright i'll learn addressables, if they're better?
Where can I learn about addressables
depends what you're doing, addressable might be overkill here
I might need it eventually
Because I'm going to be placing a variety of objects eventually
They are better but in some cases, navarone's solution is good too
And I'm assuming addressables make finding objects and materials to load into the scene, more efficient?
Awesome
instead of all at once
Materials are simple objects. If you were to load something like a hard object, like FBX, then you should use Addressables no matter what.
What is FBX
Also I cant seem to find the resource management in the asset management dropdown
is it a package I have to import?
nvm i foudn the packaage
If i were to simply tell, it is a type of 3D object. If it configured, it may include it's animations, textures. For example a literal Chicken.
what is the end goal here anyway to do this all at runtime
Oh that, would be useful to know how to create lol
Yes during runtime, placing blocks, building a bunker
I mean you could just have a bunch of SerializeField on the script and just drop your materials there and get going
thought you were trying to do over the net stuff or load large assets
Hello, working on a little dialogue system with a total of 5 audio samples.
Currently made the text work using a Canvas and TextmeshPro, and I used string to display these texts
I wanted to do the same for the audio, put them in a string so theyre in a certain order, but that is not a thing
Any other ideas how to do this effectively?
Think simple. You seem capable of doing that system without any help at all
have you worked with an array before?
Been on it for an hour but I cant think of anything within my capability
Seems useful, is it similar to a string?
technically strings are arrays
of char
but I mean an array of audio basically
Ah i was wrong 🥺
and then I could just +1 every time the mouse is pressed, for example?
yes you just move the index
ofc put a check there so you don't go outta bounds 🕶️
I think I already used an array... my mistake, I thought this was a string
yes it is a string[]
oh hahaha
I used 'private int audioIndex;'
Load is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'Building' on game object 'Player'. Getting this error in here ```\n`````` void transparentBuildVisualizer(){
if (currentBlock != null){
Destroy(currentBlock);
}
Vector3 buildPos = transform.TransformPoint(cameraObject.transform.forward * 3);
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
MeshRenderer cubeMesh = cube.GetComponent<MeshRenderer>();
cubeMesh.material = transparentMaterial;
currentBlock = cube;
// Transform the coordinates of local space to world space.
cube.transform.position = new Vector3(Mathf.Floor(buildPos.x), Mathf.Ceil(buildPos.y), Mathf.Floor(buildPos.z));
}``` ```\n``` Declaration is: ``` [SerializeField]
private Material transparentMaterial;```
you seem to have it from here then (make the type AudioClip ofc)
I'm going to learn addressables once I have more objects lol
so no int audioIndex;?
send full script using a link site
you still need that yes, but you need the type of array to be AudioClip[] not string[]
No idea the solution was that simple xd thank you so much :) learned something new today
Cheers 
!bot
⏬
📃 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.
which line is the error
I don't see Resources.Load used anywhere. Is this an addressables thing (are you even using it now)?
Did you save the script..?
I guess I'm implicity loading with the SerializeField
for the Material?
possibly
is this even the correct script lol
yes
According to the error it happened in Building script yeah
oh right
It doesn't like the fact im loading a material lol
save the script you sent, clear all console messages and start agian
a serialized field does not use Resources.Load, that would not be the cause of it. there is nothing wrong with serializing a reference to a material
Can anyone help me with a function not popping up in here: (it is a public function)
Did you reference an instance of the script (an object in the scene with the component script)?
yup
Does the function have the correct signature?
whats that mean
Show what "here" is - what is it?
that menu thats open, its got all the other functions in that script
the white
Normally Unity inspector callback/action references only allow single parameter functions.
ok, ill remove a parameter and see if that fixes it
that fixed it. but is there a way to get the value a slider is at and use that in the function?
Nope. Have another component reference the Text and set a float field then reference that component from the button or whatever that you've not shown us yet.
can someone help me understand why the hitinfo parameter is not being recognised, i think im doing something stupid but i cant get my head around it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaycastGun : MonoBehaviour
{
public Transform playerPos;
public float maxShootDistance;
// Update is called once per frame
void Update()
{
RaycastHit hitInfo;
Ray2D ray = new Ray2D(playerPos.position, Vector2.right);
if (Physics.Raycast(ray, out hitInfo, maxShootDistance)); // broken line
{
}
}
}
Is there an error?
havent run the game but the line is red, here look
What does the error say in the console?
let me check
You wouldn't need to run the application to see the error in the console
Just for reference, here are the docs for the available overloads using physics ray cast https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
thanks
If you're wanting to use the 2d variant, you'll need to use Physics 2d etc
@queen adder Yo thankyou guys so much I figured it out:
paste code on code paste website
read bot msg ⬇️ !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.
void Update()
{
Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();
if (Input.GetKey(KeyCode.D))
{
rigidbody.position += Vector2.right * Time.deltaTime * moveSpeed;
}
else if (Input.GetKey(KeyCode.A))
{
rigidbody.position += Vector2.left * Time.deltaTime * moveSpeed;
}
if (Input.GetKeyDown(KeyCode.Space))
{
if (rigidbody.velocity.y == 0)
{
rigidbody.AddForce(new Vector2(0, jumpHeight), ForceMode2D.Impulse);
}
}
}```
Nothing with your movement should be affecting your ability to jump. Checking if the Y velocity is 0 is going to be inconsistent because there's always gravity, even when you're on the ground and chances are it'll never be exactly 0
True...
if the intention for that is to check if you're on the ground, you should probably use something like a raycast or spherecast to check if there's ground below your feet instead
Id rather not...
It took me 2 hours until I gave up
I'll just give it a little wiggle room
rigidbody.velocity.y < 0.5
Would this work?
Actually lemme check
im looking at inheritance rn for uni but im struggling to see a good example for why i would use it - does anyone have one?
my personal issue is it seems like a big headache for something I could just achieve with a boolean, switch statement and an admittedly longer script
unless im just not seeing the bigger picture
This isn't really useful (tbh I just started unity yesterday) but if you make the script longer it makes you look smarter
I think
i mean longer scripts are more of a hassle to work with, especially when they aren't yours (working in a team) so not necessarily
True
but at the same time i feel like id find it easier to work with a longer script than it being split into parent and child classes
Make a script - "Weapon". Has things like damage, durability, whether it's one or two handed, etc.
Then you could make a thousand scripts - "Baseball bat", "Chainsaw", "Park bench", "Cash Register", etc. that all inherit from Weapon.
Your inventory becomes List<Weapon> and your current weapon is a variable of type Weapon and you can very easy do something like duraText.text = currentWeapon.durability without even caring about which of those thousand child objects you currently have in that slot
float yRot = 0;
switch (true){
case (buildRot.y <= 45):
yRot = 0;
break;
case buildRot.y > 45 && buildRot.y <= 90:
yRot = 90;
break;
case buildRot.y > 90 && buildRot.y <= 180:
yRot = 180;
break;
case buildRot.y > 180 && buildRot.y <= 270:
yRot = 270;
break;
}```Why isn't my switch working, not sure what c# switch statements look like
Well, you're switching on true, and true is never equal to any of your cases
so that would probably be why
Well, actually, it could be equal to any of those, if those conditions evaluate to true 🤔
is rotation 0-359? as a quaternion, like the y value of a quat
The y value of a quaternion has nothing to do with the Y axis of normal Euclidian space, it's a normalized 4D value including imaginary numbers to express an orientation
Assets\Scripts\PlayerScripts\ClientSideScripts\Building.cs(99,18): error CS0150: A constant value is expected Also this is the error i mgetting
So what's a good way of limiting rotation to 0, 90, 180, 270 degrees?
Yeah, you can't use an expression as a switch case. The only way this would be valid is if buildRot was a const, which is what I meant by "technically true"
Ah I see
You can get the rotation of an object with eulerAngles instead of Rotation, but it won't always be the form you expect it to be in. For example, an angle of 270 is identical to an angle of -90
and you can combine X and Z rotations to gain the same orientation you could by having a value on Y
coolio
What does rotation even return then if not 90, 180 etc
is it like some random float value
A quaternion. A normalized 4D Complex vector that represents a specific orientation in 3D space, without gimbal lock, no ambiguity of angles, and generally more mathematically precise, at the cost of being basically nonsense to humans
If you ever find yourself trying to deal with individual components of a quaternion, don't
I see hahaha
I have to limit the rotation of these wall assets I've made, so they place correctly in a grid block
dependent on player rotation to grid space they're placing it in
euler angles would be waht I want to use then?
Generally, you should work with directions rather than angles. You can get the direction it starts facing, and compare it to a world direction. Dot product is 1 when the two directions are facing the same direction, 0 when perpendicular, and -1 when opposite. So, you can get the current forward direction, and compare it to Vector3.forward, Vector3.left, Vector3.backward, and Vector3.right. Find which one has the highest Dot Product, that's the direction the object is "closest to" facing
That way you don't have to deal with positive/negatives, or non-Y rotations expressing the same direction
Awesome, thankyou. That's great
is it better to write your own inputs for movement with character controller or simply use the input manager
im about to just throw out the entire movement script and start over because i feel like with the way i've written it i cant really add crouching or jumping. originally i had no intentions for those because it didnt really cross my mind as that important. i likely wont do the jumping, but crouching will likely be added
physics vs character controller
my greatest enemy
I´ve been struggeling the past hour with the following problem:
I made some code in a flappy bird clone to add a point every time I go trough a trigger between pipes. Works perfectly
Now I want to make it so that if I get a game over I cant get more points even if I still go trough another pipe, but no matter what I do the points either stay at 0 the whole time or the code dosen´t work at all.
WHat should I do?
should be pretty simple by just using a bool?
but show your !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.
Ill post the code in a sec but I have a bool that checks if the bird is alive
public class MiddeloPipoScripto : MonoBehaviour
{
public LogicoScripto logic;
public SChloppyScript SchloppyLebt;
public LogicoScripto playerScore;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject && SchloppyLebt == true)
{
logic.addScore(1);
}
}
}
where do you set assuming BirdAlive to false
in another script. One sec
public class SChloppyScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flyStrenght;
public LogicoScripto logic;
public bool SchloppyLebt = true;
// Start is called before the first frame update
void Start()
{
gameObject.name = "Schloppy";
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) == true && SchloppyLebt == true)
{
myRigidbody.velocity = Vector2.up * flyStrenght;
}
if(transform.position.y > 4.5)
{
logic.gameOva();
SchloppyLebt = false;
}
if(transform.position.y < -4.5)
{
logic.gameOva();
SchloppyLebt = false;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
logic.gameOva();
SchloppyLebt = false;
}
}
aat the bottom,
ok, and does this code run?
yes that code I sent runs pefectly
here
you are just checking if your script variable is true
your not checking the actual bool itself
i might just throw out my script and character controller and work with rigid bodies instead
never really done it before so this might be a pain
Can you explain that a little more exact.
How would I check for the bool itself?
pretty much the same
MyScript.MyBool
the . access a property
Do I put that after the && ?
yes, where you have the current check, you are just replacing that
or well just adding . and accessing the variable
I get CS0117
Basically MyBool dosent have a reference. But if I change MyBool to what I called the alive status then it becomes CS0120
ye i'll just set the player to be a kinematic rigid body and code the movement
show the code
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject && SChloppyScript.SchloppyLebt == true)
{
logic.addScore(1);
}
}
}
the player itself is not what needs to be affected by physics, but the player's movements will be applying physics effects to other objects it interacts with
so if it runs into something (that also happens to be a rigid body that isnt kinematic), it should push that thing
how fun :(
what you done here basically SchloppyLebt would have to be a static variable
what you wanna do is get a reference to your script instead by using a variable public SChloppyScript myScript; then myScript.SchloppyLebt to access it
that would be yeah, but you arent using it
in this code
im trying to add an partical effect and after 1 use it gets destroyed do u know how to fix it ?
MissingReferenceException: The object of type 'ParticleSystem' has been destroyed but you are still trying to access it.
I am? 😭
check if its null when trying to use it, or dont destroy it, or dont access it after its destroyed
here
im not destoying it it just destoying it self
void CreateSmoke() { SmokeEffect.Play(); } void CreateDoublejumpSmoke() { DoublejumpSmoke.Play(); }
this is my function to use it
//First Script
public class MyScript : MonoBehaviour
{
public bool MyBool;
}
//Other Script
public MyScript myScript;
if(myScript.MyBool == true) { myScript.MyBool = false; }
yeah so the next time you run these methods, it will be destroyed therefore you cant play it
what you should do is just de activate it, or Instantiate and play one instead of playing the same one
by making a prefab and instantiating and playing it
@valid turtle something like this is what you need to do, hopefully you understand
Im trying to understand
give me a bit
i was panicking and worrying id have to redo the entire thing and replace all the components but turns out i can just remove the character controller component 
The problem I have is that it says it needs an object reference, but I have that reference like I said b4. Im so confused
yeah but you arent using it
what you have done basically is:
public MyScript MyBool;
if(MyBool)
``` which is wrong, the compiler doesnt just guess you want to use `MyBool` of `MyScript` because you named your variable that
/// I have this
public SChloppyScript SchloppyLebt;
/// and I try this
SChloppyScript.SchloppyLebt == true)
what you need to do is SchloppyLebt.SchloppyLebt == true
YourVariable.YourBool
Ohhh okay
this line public SChloppyScript SchloppyLebt; can be named absolutely anything, it doesnt relate to just 1 variable you want to access from it, you TELL it what variable you want to access via the . then typing the name of the variable you want
if (collision.gameObject && SchloppyLebt.SchloppyLebt == true)
{
logic.addScore(1);
}
else
{
logic.addScore(0);
}
}
}
this might work then?
yes, the else is pointless here though
you can jump still right?
yes
oh im stupid
i added the component to begin with
before the if statement do Debug.Log($"Collided with: {collision.gameObject.name}, bool is: {SchloppyLebt.SchloppyLebt}");
and see what it prints
NullReferenceException: Object reference not set to an instance of an object
MiddeloPipoScripto.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/MiddeloPipoScripto.cs:25)
did you assign the script in the Inspector?
i assume not
Uhh wdym by that
in the inspector of your GameObject with this script.
there is a slot you can drag something to
do you have this script on a game object?
Yes
then go to that game object
now there should be an empty slot
jup
just do a Find for now then like you do for the logic script
but Find should be avoided as much as possible usually
Where should I use find?
in Start
the same way as you do multiple times already
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
}
like here
what would the code look like? I never wrote a find function
uhhhhh what?
i see multiple of them
in your code
Sorry Im just so new to this. What do you mean by find?
Use FindWithTag to avoid misspelling GameObject as GameObjects, which is the plural version that returns an array . . .
GameObject.Find("YourObjectName");
or if it has a tag you can use the FindWIthTag
That probably wont work, because I added a tag to that gameobejct
Everything will not work if I do that I think
im confused, why wont it work
your just finding a game object by name
then accessing the component from it
Im so confused as well
would be less confusing if you had english names on the scripts and variables 😄
I know Im sorry
SChloppyScript = GameObject.Find("YourObjectNameThatHasThe (SChloppyScript)").GetComponent<SChloppyScript>();
as simple as that
To me it looks so confusing because I barely understand what it means so I call it "that whole thing"
Not sure if this is a code issue, so please don't jump down my throat. I don't know which channel to post this in.
I have a prefab containing a parent "Struct_Cannon" with no mesh attached to it, and two children. One a cube and one a cylinder.
When I instantiate the prefab, the cube does not come along, and simply isn't present.
Nothing gets deleted until the structure has less than 1 health, and here's the instantiation code:
if (!spawnedStruct) {
GameObject curCannon = Instantiate(cannon, new Vector3(0, 0.5f, 0), Quaternion.identity);
StructInitiate structInitiate = curCannon.GetComponent<StructInitiate>();
structInitiate.structActive = true;
structInitiate.health = 200f;
spawnedStruct = true;
}
else {
Debug.Log("Cannot place: cannon in way");
}
}```
The body child is active and on a plane the camera can see, but it's not being added to the scene at all.
Any help is greatly appreciated.
SchloppyScript is Type but is being used as Variable is now the issue
SChloppyScript is your variable, or wait you called it the same as your bool so whatever you named your variable
then you set the value of it to GameObject.Find(); which finds a game object with the name (string) you enter, then from the result of that you get a Component from it by .GetComponent
Check capitalization
ye dont worry
yeah thats my bad, i explain it in the message below
I just wrote it fast
That makes no sense because Middle ( the thing where the trigger is) isnt a part of SchloppyScript
I think
I dont know
Just assuming
so? thats the point of the Find
thats where you put the name of your game object that has the SChloppyScript
idk what you name it
Schloppy thats what you name it
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
Wait I think I understand my mistake
Do i put it Voidstart of the Bird script or the trigger script?
the trigger script
I was like;
why would I find it where I already am
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
}
Hey @deft grail you see any immediate issues with what I'm doing? Can't figure this out
yeah looks fine
from the code you provided so far, looks like it should work fine unless you are instantiating a different prefab
I am not
But the cube just isn't being included in instantiation
But why Schloppy? thats just the line of code where I name the bird. Nothing else.
because .Find finds a game object with a SPECIFIC name
so if thats what you name it then thats what you need to find
this is why Find isnt good either, because if you rename it boom the code is broken
what you are trying to find is the Script that has the bool
yes
you cant find the bool, but you can find the script
thats your goal yes, find the script
SchloppyLebt = GameObject.Find("SchloppyLebt").GetComponent<SChloppyScript>();
like that
I think
Found the issue: I had the script intended for the prefab as a whole attached to the child object.
well no, is your bird ( i think the bird is the one with the script?) is the bird named SchloppyLebt?
The bird is actually named Poppy but when I run the game the first line of code renames it to Schloppy
void Start()
{
gameObject.name = "Schloppy";
yes, which is why im telling you to find Schloppy because thats what you name it
if you look on the left you can see "Poppy"
Okay okay
understood
and now it should work?
or do I need to add anything else?
yeah as if i know that a random GameObject named poppy is your bird 😂
as someone helping i have ZERO clue that its what it is
public class MiddeloPipoScripto : MonoBehaviour
{
public LogicoScripto logic;
public SChloppyScript SchloppyLebt;
public LogicoScripto playerScore;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log($"Collided with: {collision.gameObject.name}, bool is: {SchloppyLebt.SchloppyLebt}");
if (collision.gameObject && SchloppyLebt.SchloppyLebt == true)
{
logic.addScore(1);
}
}
}
i think so unless something is missed
Thats why I told you 😭
its been confusing so far so might be missed
yeah looks fine i guess
OMG
IT WORKS
I LOVE YOU
Now I need to understand why it worked and then everything is perfect xD
because you thought a variable can be directly used as the bool you wanted because you named it that
yeah sure
can someone help me find the right refrence?
using BepInEx;
using UnityEngine;
[BepInPlugin("com.yourname.controllerrotator", "Controller Rotator", "1.0.0")]
public class ControllerRotator : BaseUnityPlugin
{
private void Update()
{
// Check if the right trigger (GrabPinch) is pressed
if (SteamVR_Actions.default_GrabPinch.GetStateDown(SteamVR_Input_Sources.RightHand))
{
RotateController();
}
}
private void RotateController()
{
// Find the tracked object for the right controller
var trackedObject = GameObject.FindObjectOfType<SteamVR_TrackedObject>();
if (trackedObject != null && trackedObject.isValid)
{
// Get current rotation and apply a 90-degree rotation
Quaternion currentRotation = trackedObject.transform.rotation;
Quaternion newRotation = currentRotation * Quaternion.Euler(90, 0, 0);
trackedObject.transform.rotation = newRotation;
}
else
{
Logger.LogError("Tracked object is not valid.");
}
}
}
using BepInEx;
using UnityEngine;
[BepInPlugin("com.yourname.controllerrotator", "Controller Rotator", "1.0.0")]
public class ControllerRotator : BaseUnityPlugin
{
private void Update()
{
// Check if the right trigger (GrabPinch) is pressed
if (SteamVR_Actions.default_GrabPinch.GetStateDown(SteamVR_Input_Sources.RightHand)) //I do not have the refrence to these actions
{
RotateController();
}
}
private void RotateController()
{
// Find the tracked object for the right controller
var trackedObject = GameObject.FindObjectOfType<SteamVR_TrackedObject>();
if (trackedObject != null && trackedObject.isValid)
{
// Get current rotation and apply a 90-degree rotation
Quaternion currentRotation = trackedObject.transform.rotation;
Quaternion newRotation = currentRotation * Quaternion.Euler(90, 0, 0);
trackedObject.transform.rotation = newRotation;
}
else
{
Logger.LogError("Tracked object is not valid.");
}
}
}
!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.
/// This is a reference right?
public SChloppyScript SchloppyLebt;
/// so why did we need to put this here
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
the 1st line is CREATING a variable
the second one is assigning a value to the variable you created
try commenting the second line with //
and see what happens
commenting?
//This is a comment
/*
All
of
This
is
commented
*/
with // or /* */ you can comment
Understood
paste the code correctly in a website, and explain the actual problem with a question
By creating a variable you mean its creating a reference to the other script right?
oh
mb
its not creating any reference no until you assign a value to it either in the inspector or in code
So the reason I put
public SchloppySscript SchloppyLebt;
is not to tell the current script to do anything with the other script?
wait wdym?
you could also use ChatGPT
It helps most of the time
this is a variable
public is the access modifier, so it can be private, public, public static, [SerializeField] etc
SchloppyScript is the Type, this can be int, bool, Rigidbody2D, BoxCollider2D, float etc
SchloppyLebt is the NAME of your variable, this can be almost anything that you want with a few exceptions
I did, thats what I used to make the code.
(which is why both of you lack the basics of C# and Unity)
Ohh I have bad experience with that.
I only ever use it to solve problems
But it needed something called "Valve.VR" Which I can't get because it's refrences in "Assembly-CSharp"
Oh I lack them because I just started out
like 2 days
literally
your best bet would be #🥽┃virtual-reality or looking on google
it might take a while in the channel for someone to respond though
I have
then ideally you shouldnt start with VR, its not too hard but its quite the bit harder than normal Unity
But I'm making a mod
I don't even have unity installed on my system
Plus
I (think)
I know the problem
I can't refrence "Assembly-CSharp"
then i dont think you can get help here
because you probably need to install a package in the package manager or something not sure
and game modding isnt allowed in this server either
bruh what 🤣
yes?
i dont think thats a thing
wdym?
So it can be acessed by anything, the type is a script and the name is obv. the name
i mean your using C#, how can you reference it
yeah
There u go
And I use:
public SChloppyScript SchloppyLebt;
To make the current script able to work with content from SChloppyScript, right?
yeah kinda
Then how can I use all of ths?
kinda?
use what, UnityEngine and BepInEx? because thats how they are supposed to be used
same way you can do using System; etc
And why can't assembly be used?
Im so sorry btw, I hope I didnt waste too much time
how can i stop it from goint to infinity ?
https://prnt.sc/NC9JIBCGePqK
Kinda means what, if you can explain?
uhh i dont really know tbh 🤣
idk why i said "kinda"
okay okay xD
because thats just the language you write the code in i think?
it doesnt make sense to add it by using ...
your issue has nothing to do with c#
doens't using Mean your refrencing it?
(how do u do the "using" thing btw?)
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
// This does something else than making my script able to work with content from another script?
this? just use 2 ` instead of 6
this sets the value of your variable to an Instance of a SChloppyScript script
U know, your right
vr may be too hard
Is there a easy unity game you think would be easy to mod?
sure, but this has nothing to do with VR either really 🤣
idk anything about game modding, the most popular thing i see in this server is vrchat but i have no idea if thats any sort of "modding"
(it does tho, bc I'm trying to find the game obect and rotate it (along with its collision) 90degrees
ewwy
no vrchat
sure but this has nothing to do with the rotating or finding game object
actually 🤔
dont you just need using SteamVR; or something
well either way, there you go thats the problem
I know
Its so hard for me to grasp this. Can you explain that in a more simple version maybe?
public int MyInt;
MyInt = 5;
``` 😂
if your talking about modding "bean", then dont.
modding isnt allowed in this server lol
Yes thats what I understood before.
just make your own game
not sure what the point of modding games is anyway
some random games
But a bool dosent have a value. Its only true or false no?
well that is a value
but what does a bool have to do with this?
your finding and setting a script, not a bool
because we were trying to fix that I couldnt stop getting either 0 points or 1 point even if the bird is ded
and I tried that with a bool
yes because you were trying to get the bool from thin air
you need to get it from your actual instance of your script
which is what you did by making a variable and setting its value to an instance of the script
Okay but this:
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
isnt reference the bool?
yes
you can do MyBool = GameObject.Find("Schloppy").GetComponent<SChloppyScript>().SchloppyLebt;
to reference the bool directly itself
OHHH
but if you do it once in Start that wont help anyway
Sorry I cant read
I forgot the beginning part of SchloppyLebt
so I was like
how are we getting a value for the bool if we arent talking about the bool anywhere
MyBool wont have the changes that SchloppyLebt will have
it just sets it once
because in these 2 lines of code you arent 😂
only in the if statement
But SchloppyLebt is the bool no?
public bool SchloppyLebt = true;
So if we do this:
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
we are talking to (or about) the bool
just because you named this SchloppyLebt doesnt mean you are accessing the bool
you can name it whatever you want
it wont change a thing
this line has NOTHING to do with your bool, or any bool
So the problem started here:
if (collision.gameObject && SchloppyLebt.SchloppyLebt == true)
{
logic.addScore(1);
}
I wasnt using
SchloppyLebt.SchloppyLebt
But instead SChloppyScript.SchloppyLebt
So we made this:
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
But if this 2nd line of code dosent have anything to do with the bool, why did the 1st line now know what to do?
.SchloppyLebt is accessing the bool from your script
so SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>(); or public SChloppyScript SchloppyLebt;
have nothing to do with your bool
these just reference the SCRIPT
yes
So if I ever do something like this agian, I would need both
public SChloppyScript SchloppyLebt;
// and
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
to make points only appear when the character is alive
because the public line isnt enough of a reference
you could skip the 2nd line for example if you assigned SchloppyLebt in the inspector
what you can also do is
in the inspector it is only a checkbox
//In your SChloppyScript
public static SChloppyScript Instance;
void Awake()
{
Instance = this;
}
and in your trigger script do SChloppyScript.Instance.SchloppyLebt == true
yes? a bool is true or false, 0 or 1, yes or no, why would it be something other than a checkbox?
how do I assign it then`?
you cant because your trigger script is a prefab
thats why you need either this
or what you did with a Find
or assign the variable when you Instantiate the pipe
because its bad on performance i think?
if you change the name of your GameObject/Tag/Whatever find your using
it will fail because you changed the name
and because theres better ways of assigning a variable
okay
the best one would be when instantiating it
But thats impossible if I like make something, then decide to add something else, then I have to delete the first thing and remake it so the 2nd things works perfectly?
wdym
add what
depends what your adding and changing?
idk
I wanted to create a FlappyBird clone
So I made the basic game with jumping, pipes and game over
To make the pipes I make a prefab so it dosent infinetly creates pipes
Then after Im basically done I want to add a Score system.
But to not use find I would need to delete the prefab and recode the pipes so I could properly add the scoresystem to avoid find
why would you need to delete the prefab and recode the pipes?
you just need to change the way you reference
because you said I cant reference to a prefab
a prefab cant reference scene objects yeah
so you use one of these 3 methods / something else to fix the issue
Okay
I think I will just leave this how it is. I think I half understood what you kindly tried to explain to my stupid monkey brain.
We fixed it and I can move on to the next addition for the game haha
as long as for your next project / bigger project you know whats better and whats bad, then thats all that matters
for your first or even second or even 10th project if they are all small/prototypes
then bad code doesnt really matter
I kinda didnt. I just dont want to bother you anymore XD 😭
Using the bool value: The boolean SchloppyLebt.SchloppyLebt is part of the SChloppyScript. If you don’t assign SchloppyLebt to the right object using GameObject.Find and GetComponent, the script wouldn’t know which instance of the SChloppyScript you're referring to, making it impossible to check its SchloppyLebt value.
This is what ChatGPT spat out.
Now I get it
ah said the same thing as me but worded different 😄
as long as you get it then thats good
The onlything I dont know is the fetch specific thing.
If we dont talk about the bool directly, how does the game know Im talking about that specific code
Like how does it know which component to fetch if we didnt specify
how does it know your accessing the bool?
because you access the bool with .SchloppyLebt
oh so
oh then it doesnt
then it errors
it would work alone if you assign it in the inspector
thats it
or if you use ONLY the 2nd line also, would work
because it only knows to fetch .schloppylebt by needing it for the point adding
It didnt. that was the start of the issue if you remember
if you use only the 2nd line, in the if statement
it will work
by the 2nd line you mean the one with Find correct?
thats what i mean at least
if (collision.gameObject && SchloppyLebt.SchloppyLebt == true)
{
logic.addScore(1);
}
if you did && GameObject.Find("...").GetComponent<TheScript>().SchloppyLebt == true it would work
OHHHH
Okay
My god
How do you even have the energy to explain this to me
wow man
because i have nothing else to do lol
XD
is there any solution for pink items?
fix the material/shader
GameObject.Find("...").GetComponent<TheScript>().SchloppyLebt == true
This line of code is basically cut in half in my code.
Thats the thing I didnt understand.
this is the same thing as the other one except it doesnt store it in a variable