#💻┃code-beginner
1 messages · Page 234 of 1
target is null
Make target not null
Why is target null? Did you set it anywhere?
I mean pretty much. We don't know how this script is handling that target variable.
This?
Put cs if (!target) return;after line 49
does not work
i am so confused
Why on line 20 is it ```cs
if(target != null)
FindTarget();
Wouldnt you try to find a target if target WAS null?
What error did you get?
the same but on different line
Surely if the target is null it would have returned the function.
So the problem was solved, you've got another problem.
erm yes
The real solution would be to simply not call any of these functions if you've not got a valid target
why is this so inconsistent? (varies on framerate)
public void MoveTowards(Vector2 targ) // called in update, targ is usually mousepos
{
rb.MovePosition( Vector2.MoveTowards(rb.position, targ, Time.fixedDeltaTime * speed ) );
```using `fixed` is fast at high fps but slow at low fps,
using `deltatime` is the other way around
Remove time.delta time
wait holdon let me look at .MovePosition()
Never mind dont remove it
i cant find which is disturbing the rate, it should work fine when moving via transform
Are you calling this in update or fixed update? Also, you ought to always simply use regular delta time.
and MovePosition is instant move as well, so they should be similar
Regular delta time called in the fixed update would use the fixed delta time
I qouted this
using fixed is fast at high fps but slow at low fps,
using deltatime is the other way around
this is the weird thing
// called in update
yes
I have a Turret which should not Target anything when the target is not in range.
show code ihomas 💀
actually imma try transform.position, it should be really fine if that
The ordering on those functions in Update seems strange.
Wouldn't it make more sense to:
- Check if the current target is null or not in range. If so, get a new target.
- Then rotate towards the target if you have one.
Fixed delta time would just be a fixed value. Delta time in update would be the time elapsed since last frame.
That is what I want but I dont know how to do that
Hey! How you are checking a method inside an if statement?
Is it possible something like that?
you know how you do void methodname()?
Yes
void is just the return type
I know that I mean how he checks the method
if(target == null || !CheckTargetIsInRange())
{
FindTarget();
}
if(target != null)
{
RotateTowardsTarget();
}
Something like this probably.
so if i put, bool methodname(), i can check if methodname is true or false
Not pretty but meh.
Thats fine
yea, ive been using deltatime just until i noticed that my character moves super slow on high fps, then i tested both
// rb.MovePosition( Vector2.MoveTowards(rb.position, targ, Time.deltaTime * speed ) );
transform.position = ( Vector2.MoveTowards(rb.position, targ, Time.deltaTime * speed ) );
```this is fine, though the `rb` version isnt... hmm..
You need to be calling the rb one in fixed update
then what was this comment about
can or cant?
if a method returns a bool you can use it in if cs bool check() {}
Now, I am checking it and it says cannot apply operator to the type void
yes
but you obviously need to return something there
Only for bools?
anything bool can go in ifs
I can check it only for booleans?
any return type that isnt void
You just have to make the correct comparison
it's only bools (unity objects just secretly turns themselves into bools)
dont worry about what that means
void means no return type. An if statement checks a condition or expression. It must result in true or false. If a method has a boolean return type, then it returns true or false; hence, it is valid to use within an if statement . . .
Yeah I know what the void means. I was just confused of how we check a method because I have never checked a method in an if statement before.
It depends on the return type (or if it has one). It doesn't matter if you use a method, variable, or an expression, so long as it returns true or false . . .
im making flappy bird game. but i made the level generator work on time. like every x seconds it makes a new bc and walls and every x seconds it deletes. but i cant find a equlibrium where i dont eather catch up to the generator or or where the deleter catches up to me. and i tried to generate based on player distance but i just falied miserably any ideas?
That's usually based on distance, not time
There are about a million Flappy Bird tutorials, you could look at how they do it
Hello
I'm having another problem, or more like knowledge issue:
I'm currently trying to make a code for random spawn position and random movement direction
Random position does work - it is in a different code
But when objects spawn - they're moving in both directions at the same time, instead of choosing one of two random directions
void Start()
{
direction = new Vector3[2];
direction[0] = Vector3.right;
direction[1] = -Vector3.right;
}
// Update is called once per frame
void Update()
{
BubbleFishSwim();
}
private void BubbleFishSwim()
{
int index = Random.Range(0, direction.Length);
transform.Translate(direction[index] * speed * Time.deltaTime);
}
Well you call BubbleFishSwim every update, and in that method you choose a random direction from that array.
So literally every single frame it's deciding "do I go left or right?"
It makes sense
I assume you want them to choose a random direction ONCE, right?
And move along that direction?
Yeah
Each spawn they choose the direction
I don't really like how we're choosing that direction but whatever you get the idea.```cs
Vector3 chosenDirection;
void Start()
{
direction = new Vector3[2];
direction[0] = Vector3.right;
direction[1] = -Vector3.right;
int index = Random.Range(0, direction.Length);
chosenDirection = direction[index];
}
// Update is called once per frame
void Update()
{
BubbleFishSwim();
}
private void BubbleFishSwim()
{
transform.Translate(chosenDirection * speed * Time.deltaTime);
}
Idk why you're being so secretive of your class/variable names.
It doesn't matter.
why dont just
direction.x=Random.value<0.5?-1:1;
```ofc not work if you have multiple direction
You can, just using the code they provided since they probably understand that.
And not... a terinary.
what does the code that's giving the error look like?
That works, but I also want fish to know which direction they should move in, depending on what Xposition they spawned in. Can you help me with that as well?
void Start()
{
fishX = new float[2];
fishX[0] = -6;
fishX[1] = 5;
}
// Update is called once per frame
void Update()
{
bubbleFishY = Random.Range(-6, -12);
}
public IEnumerator SpawnBubbleFish()
{
while (true)
{
int index = Random.Range(0, fishX.Length);
yield return new WaitForSeconds(bubbleFishSpawnRate);
Instantiate(bubbleFish, new Vector3(fishX[index], bubbleFishY, 0), transform.rotation);
}
Hey, guys! I am currently making a flappy bird game and I have a small issue. So, I want my tree logs to deactivate whenever they touch the other collider. For one reason, it doesn't happen and I wrote some code for that with an OnTriggerEnter2D() method. Check my code:
{
[SerializeField] private GameObject treeLogs;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("LeftBound"))
{
treeLogs.gameObject.SetActive(false);
}
}
}```
To note that logs are being instantiated everytime.
Also, I have box colliders to both of them like and my other invisible game object and my tree logs as well checked for IsTrigger
treelogs is already a gameobject
if this script is on the log, you dont even need the treelog field
does the left bound have rb?
i think your log doesnt need a rb, only the bird and the bound need
Tree logs is a prefab yeah. The script is attached to this prefab and I have a field for that. Also, my left bound game object doesn't have an rb.
I don't have rb to my logs
Yeah I know that
is there any tutorial to make spline mesh work in runtime like I want road laying mechanic using splines.
problem, solve?
The error tells you the script and line number. Otherwise 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.
I tried googling but didn't find a way to make it work at runtime.
You're missing a closing } in your fixed update.
Then it likely doesn't exist
maybe not on google but does anyone here can help me with it..?
It cleared, now it has 3 errors left.
Is your IDE not underlining the error?
No.
"Attach" is there and leads to a form, to run it.
I've been having problems with it, but still manage to script.
Then you need to configure your !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
VS2019.
It's a requirement to ask questions here, regardless if you manage without it.
It's not going to fix your errors. It's going to highlight them, and your IDE will auto complete things for you.
So what is it highlighting when you double click those errors?
whoopsie memory leak?
Show a screenshot, let's see if it's actually configured.
That wasn't to you
Okay, sorry
You removed the braces entirely.
You were missing a closing brace. I don't know how you interpreted that as deleting the opening one.
not a memory leak, infinite recursion... check the stack trace of the SO and you'll see where the problem is
Anyway I can see this going to be a lot of hand holding, so I'm going to move on. Good luck.
hello pulni ive heard good things about you
Like 2 years ago
Please tell
ooh, curious 😄 thanks to whoever for the kind words ❤️
does anybody know how to solve this?
I have a teacher lesson I can show you all.
What is missing from this screenshot
I'm seeing differently now.
there is
Seeing the answer?\
🤔 ;
Wait, i'm going to edit it.
why have ; when finishing method
Have you tried reading the full error in the Console window? Or reading the warning that your IDE is showing by hovering over the yellow underlined area?
Gotten too used to python or js or smth. 
i did get rid of that error but
I just dont get why its not jumping after once
That area is still underlined in yellow
whaat
It was underlined by IDE
and you didn not have {}
it says it is unused
I hate to usem them too tbh but you can not use them if you have an if staement for exampl
and its single line
thx lemme check it
oh my god
i just forgot to capitalise the 'd' in OnTriggerEnter2d
lemme see if it works
its working now
but i still wanna cry
Hey guys, I have a class with
private bool Available;
public bool getAvailable {get; set;}
Now I have another class that has an OnCollisionEnter to detect if this game object is colliding with the other game object with that class above
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.CompareTag("Bricks"))
{
}
}
I mean I wanna access and change the value of Available in the other class after the collision was detected.
But how do I know what game object I collided with to call the method, I mean other.gameObject is not guaranteed to be the class above
So how do I get to the getAvailable method ?
You get the component with GetComponent . You can do that in your if.
Just use TryGetComponent to check whether you hit an object with that component, while getting it
I’d also reconsider your naming for properties and variable. Capital letters are by convention used for properties. Get available suggests it’s only used to get but it has a setter.
also if your Available/getAvailable is written exactly as above they are two unrelated variables
Oh yeah that too. You need to specify the backing field in your case.
Like this ?
when I crouch, I adjust the height of the controller but It pushes the ground checker down also and it loses the ground check, how do I avoid doing that?
you have to assign that value to something (which would access the getter) or assign something to that (which would access the setter) but yeah basically. you still have to account for the possibility that the component doesn't exist and thus would be null, which you can do with an if (e.g., if the component != null, do that)
also, i'd avoid that kind of plain public setter, since it basically converts your property to a public variable
also if you're going to get the component and check if it's null i'm guessing you don't need to check the tag
since i'm guess only items tagged "bricks" have a "brickitem" component
._.
um... no if you want to assign you'd do getCanPick = false;
Oh ...
properties are methods that act like variables syntactically
Thank you
if I wanna compare this in an If to check if it's true or false, I'd do getCanPick == false; right ?
Can someone check my detection system and tell me where my logic is wrong please? Sometimes it will work and sometimes it won't, it will either give me one result all the time or work randomly
https://hastebin.com/share/bomubezapi.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
whats wrong with this
you tell us
I'd suggest drawing some debug rays to debug it. On the first glance, the code looks fine.
If it works, then what's the issue?
why use == in one and != in the other?
thank you cuz i thought there should be no issue
OnTrigger exit
What about it? Also, does what Steve said, fix it?
because its checking if the pad is not there
god
im stupid
Exit would be called when a collider exits it. If you expect the Pad to exit the collision, you should check if it's the tag.
it works now im just stupid
so on enter if it's Pad yo set to true and on exit if it's not Pad you set to false? Seems very strange
setting controller height lower when crouching moves everything downward including groundcheck, which fails and gravity starts going up very fast, how do I prevent it?
if ok
You have to also reposition the collider. Scaling happens from the center, so you naturally need to move it down to compensate.
ah, what is the center?
it is like this
everything is connected to the controller, it is difficult 
it's just a few things that you need to "move around"/adjust together
this is the first person play thingy, I think it is the collider, then the ground check
how would changing or moving the center help? I cant seem to grasp it yet 
wouldnt that mean the ground check would still move regardless or I am missing something
Hello, I need some help rotating a projectile towards the direction of movement. Here's my code:
void Update()
{
transform.Translate(direction * speed * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(direction);
if (transform.position.z > 2)
{
Destroy(gameObject);
}
}
}
However, when modifying the rotation, the position is also changing for some reason and it's not longer following the expected trajectory
from the way I visualize it, does it work like this? or I could be wrong
some problem again with the animator
it seems to be going the same way and not connecting right
ah wait, is it like this?
but then, I dont know how to adjust the center, since if i change it to compensate the final transform, when it is long, it would be floating
Hello guys. I wanted to ask this question its somehow code related. So let's say you want to learn a coding concept for unity. Is it better to learn it from documentations first then watch tutorials about it or watch tutorials first?
sometimes I get jammed, and need help here, but you could start with guides that are good, but some are ill and are not so precise
Do whatever works for you, there is no "better"
Heyyy
Is there someone who can teach me how to make third person controller real quick
I am stuck at that problem since two weeks
🥺🥺
I think you'll learn more from documentation as it forces you to think about the concepts for yourself. Most tutorials tend to spoon feed the information. But they are a valuable resource for when you can't figure stuff out on your own.
is like this? 
Unity offers a 3rd person controller ready to use
Posting random drawings here isn't going to be useful for anyone.
the green one is groundcheck, red is the playerbody, i cant figure out what is the center since everytime i simulate it in drawing, the groundcheck falls down
lmao fr..
liek are u just pretending these are happening?
or are they actually happening
I dont know how it works
no one told me how the center is relevant
Nahh bro actually I wanted to learn from scratch
So that in future I can use my own animations and logic
on the character controller..
theres a center parameter
u'll need to tweak that to fit ur smaller size
The projectile is deviating itself from the trajectory towards the mouse pointer (white circle)
The center property of the CC defines where the center of the collider is. If you're scaling the height of the collider, you have to move it to compensate. That's it, that's all.
Oh ok then I'm sure there are plenty of tutorials on that on youtube
Is there any vc present in this server 🌝
No
I will be happy to connect with you guys on vc
I am still learning, I hope it is ok
I am a bit slow
for me my collider is 2 tall.. and my center is 0..
when i crouch its 1 tall.. so i reset my center to .5
Does anyone know why this could be happening ??
sorry spawn, steel, I get it now
okok, I will do my best 
im not sure what u mean.. but ofc the position is changing
ur changing it ^
Okay so basically I want to make a simple 2D race game between 2 cars 1 car moves at constant speed and isn’t playable, the other moves when I press the space key. Now I am stuck with collision I want the game to freeze and display a message “the winner is:” when the one of the cars reach the end line but the cars keep going.
I made colliders and made them trigger but doesn’t work, I have 2 scripts which I will send down here 👇
using UnityEngine;
using UnityEngine.SceneManagement;
struct CarInputState
{
bool isAccelerating;
public CarInputState(bool i_isAccelerating)
{
isAccelerating = i_isAccelerating;
}
public bool IsAccelerating => isAccelerating;
}
public class CarController : MonoBehaviour
{
Collider2D colliderr;
CarInputState inputState;
float speed = 1f;
float acceleratingspeed = 2f;
bool isAccelerating;
void Start()
{
// initialize whatever needs initialization
if (gameObject.CompareTag("Player"))
{
isAccelerating = true;
}
else if (gameObject.CompareTag("ConstantSpeedCar"))
{
isAccelerating = false;
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
if (isAccelerating)
{
Vector3 position = transform.position;
if (Input.GetKey(KeyCode.Space))
{
move(position);
}
// implement game logic
}
}
void FixedUpdate()
{
if (!isAccelerating) {
Vector3 position= transform.position;
position.x += speed*Time.fixedDeltaTime;
transform.position = position;
}
}
CarInputState getInputState()
{
//capture inputs here
if (colliderr.gameObject.CompareTag("Flag"))
{
StopGame();
}
return new CarInputState(isAccelerating);
}
void move(Vector3 i_deltaPosition)
{
// implement the move code for you car
float deltaTime = Time.deltaTime;
i_deltaPosition.x += deltaTime * acceleratingspeed;
transform.position = i_deltaPosition;
}
public void StopGame()
{
Time.timeScale = 0.0f;
}
}
Yeah that line is translating it towards the desired direction, it isn't until I rotate it in the following line that the position gets changed in an undesirable way
Anyway I fixed it by changing only the graphics rotation instead of the entire object
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class RaceCountdown : MonoBehaviour
{
[SerializeField] Text countdownTextUI = null;
[SerializeField] Text WinnerTextUI = null;
Coroutine countdownRoutine = null;
void OnEnable()
{
countdownRoutine = StartCoroutine(playCountdown());
}
void OnDisable()
{
if(countdownRoutine != null)
{
StopCoroutine(countdownRoutine);
}
countdownRoutine = null;
}
public bool IsCountdownRunning => countdownRoutine != null;
IEnumerator playCountdown()
{
// Bonus : Implement this coroutine
countdownTextUI.text = "3";
yield return new WaitForSeconds(1);
countdownTextUI.text = "2";
yield return new WaitForSeconds(1);
countdownTextUI.text = "1";
yield return new WaitForSeconds(1);
countdownTextUI.text = "Start";
yield return new WaitForSeconds(1);
countdownTextUI.gameObject.SetActive(false);
}
void applyCountdownText(string i_text)
{
if(countdownTextUI == null) return;
countdownTextUI.text = i_text;
}
void onCountdownEnded()
{
enabled = false;
}
}
If anyone can help it would be appreciated. 👍
!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 am sorry.
well, it should be basically what i suggested.. When crossing the finish line, you can lerp timescale to 0. or instant if you want
Hi team. Colliders: I have an awkwardly shaped game object. Is the best practices just to make a whole bunch of simple colliders, one convex, or is there a good asset to support auto creation of a bunch of colliders? Do I merge colliders after, is that a thing?
Thanks in advance!!
mesh collider?
multiple primative colliders yes
is it a rigidbody?
if a convex collider works for u use it
use primitives if it makes sense
good way to do it.. graphics and logic.. two seperate peas in a pod
Sooo if i have an ability that my character can equip, and i want to use it, and it's for example a throw grenade ability, and the character moves the hand as an animation, how do i connect that? I mean the animation is not on the character but on the ability that i equip (other example would be how do i place the hands where they are supposed to when i spawn a gun on the player)
i think ur doing it bass ackwards
u should spawn the gun onto the hands
you can instead use Unity's Animation Rigging package.. that will allow u to assign bones from ur character to be attached to the gun..
and then when u move the gun.. the bones you chose will work along with it.. sooo ur character animation would still play.. except his arm for example would just be tracking the gun
Yeah but i mean if i have a reloading animation for the gun, not only the gun moves but the hands are included in that too- the animation is on the gun tho so i am a bit confused
thats what that animation riggging package would do..
u would assign the arm/ and hand bones to track the gun.. the rest of the body would animate like the character normally would.. the hands would follow along with the gun..
Yeah i know but ._.
doesnt matter if ur animating the gun
the arms would just follow
the gun would still need to be attached to the player somehow.. maybe not the hand bones.. but maybe the main root so it follows along with the position of ur character
Yeah but if i want to have a reloading animation where the hand doesn't follow the gun but ... Is included in the animation, so it does something
If i spawn any gun, there must be a reference to all the bones in the hand for the animation to play
Is that automatically or-
🫠
look up some resources on it Unity Animation Rigging Package
see if it makes sense for u to use.. thats all i can suggest
#🏃┃animation is probably a more appropriate channel btw
I've been just sticking all weapon animations on the character itself. Not too sure how having it on the weapon would work.
I'd probably just stick local animations on the weapon like firing animation
ya thats what i do too
the gun is animating within a parent gameobject.. and i then add that to the character
I'm learning more about interfaces and I have a question.
an interface can have methods that you must implement in the class using the interface. is this also possible with variables?
for instance, if I have a class that implements IInteractable which has an enum EInteractionTypes. how do I make it so the class implementing the interface has to implement a variable of type EInteractionTypes?
Interfaces can force properties to be implemented, but not fields. So make your member of type InteractionType a property
can't say I understand that
interface ISample
{
InteractionType Type { get; set; } // read, write
}
ooooh
"variables" as you call them, are in reality fields
A property is designed to access a field, and to optionally do logic on the value when the property is get/set from other code
Properties can be made read-only by omitting the set accessor
yea I've used them before, didn't know they were called properties though xD
thanks, I think I can figure something out now 
It would have one, ok I'll use a bunch of simple colliders for now. Thank you!
properties are just getter/setter methods, which is why you can add them into your interfaces (not including auto properties though)
that makes sense
Is there a way that this can be done without the Out?
I only want the bool value but it seems the out parameter is required
You can discard it by passing out _
In some cases the underscore has a special meaning, it's treated as a discard
alr so i need help with this code. i have that code on a capsule model with a block hitbox and the Rigidbody physics
my whole player model rotates and fucks the physics so my player moves without anything pressing
and i dont know how i can do that the player moves just on X axis and not the Y axis
public class MouseMovement : MonoBehaviour
{
public float mouseSensitivity = 500f;
float xRotation = 0f;
float yRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -89f, 89f);
yRotation += mouseX;
transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
}
}
Firstly you should not be using deltaTime there
secondly do not rotate using transform use the rigidbody
But what is he rotating? Is this an fps?
#unity #fps #tutorial
In this series, we are going to create a first-person shooter game in unity.
We will learn how to develop all the different features that are common in FPS games.
From basic movement to shooting modes, impact effects, animating the weapon models, ammo management, enemy ai, and more.
Full FPS Playlist:
https://www.youtube...
and chat gpt
and some own
i agree
this should be the standard vetting for unity tutorials 😄
Someone knows how to fix this error?
Saving has no effect. Your class 'UnityEditor.WebGL.HttpServerEditorWrapper' is missing the FilePathAttribute. Use this attribute to specify where to save your ScriptableSingleton. Only call Save() and use this attribute if you want your state to survive between sessions of Unity. UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
I've created my class HttpServerEditorWrapper but idk what to do with it
tbh the message is very self explanatory, either add the FilePath Attribute or don't use Save
anyone know how to fix this photon vr issue also this is the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.VR;
public class ChangeHeadCosmetic : MonoBehaviour
{
public string Head;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("HandTag"))
{
PhotonVRManager.SetCosmetic("Head", Head);
}
}
}
No fix, Not Implemented means Not Implemented
probably means you need to implement it
you think it requires an override?
yep, otherwise it would be very weird to exist
(and btw, it's probably explained in the documentation @median steppe 🙂 )
@median steppe is SetCosmetic marked as virtual?
im using tutorials for a gtag fan game so
and that is relevant to the problem how?
that is a possibility, but check if the method is virtual anyway
how do i replace a child of an object with a prefab
how do i do that
is that method part of your code actually? can you show its code? or just "go to definition" and show what's there?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.VR;
public class ChangeHeadCosmetic : MonoBehaviour
{
public string Head;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("HandTag"))
{
PhotonVRManager.SetCosmetic("Head", Head);
}
}
} this is the script
sure, sure, but what about that PhotonVRManager class and its SetCosmetics method? Can you show that?
i dunno what those words mean
wtf is UnityEngine.windows?
Sounds like you named one of your own classes Input so it's conflicting with Unity's
i dont know
huh?
oh
yeah
If you need to always fully qualify that Input as UnityEngine.Input, then you have your own class Input in the project
i dont no i opened the script like that
see
What even is the question here
that looks correct
What happens if you remove all the UnityEngine on line 19? I guess nothing, it's grayed out so it means it can be removed
yes but i dont know why
where did UnityEngine.windows come from, it's your code after all
i know
but y the UnityEngine.windows
no
Yes
code does not write itself, perhaps pay more attention when your IDE offers you solutions
yo
wt hell
In VS 2022 when you type the completion list appears. In that version the list is more complete, and for some elements, when you complete it, it'll automatically add the missing using directives at the top
That's 100% what happened and you didn't notice it
I just wanted to say I know what my problem is but i wanted to ask whats the best way to deal with it. Attack is running constantly with no down time so should I add down time to each if statement in Attack or should I add it to Update() after i call Attack? I'll send an image of what the code does for now
https://hastebin.com/share/ilajucunoc.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this seems like it should be simple but I need this part to rotate its X axis so that the barrel points at the sphere
ive built out this scroll wheel inventory system... and im trying to brain storm a way to allow gaps in it... like only populating as u pick things up
https://www.spawncampgames.com/paste/?serve=code_960
i have zero idea about how to do this... except possibly requiring a <List> vs the Arrays im using now
thats how i feel i get shot playing Modern Warfare now-a-days
bullets be wrappin around walls n shit
lol
it is simple tho..
u need a gameobject parent thats holding the barrel.. making sure that the barrel is lined up with the Z axis
then you can use multiple different Look methods to look towards that sphere
I can't just use the look method because it aims with two seperate game objects
I need the selected one to only rotate its x axis
the ez way to do that is to use its own Y and Z coordinates
and use the X of the thing u wanna look at
(target.x, cannon.y, cannon.z)
what do I use this vector for? the euler angles?
its the position
ur looking towards a vector3 position..
theres a LookAt() method that does the rotations for u
// look towards the target on the x and z but straight ahead on the y
// Get the target position with the same y-coordinate as this object
desiredLookTarget = new Vector3(lookTarget.position.x,transform.position.y,lookTarget.position.z);
// Calculate the rotation needed to look at the target position
Quaternion targetRotation = Quaternion.LookRotation(targetPosition - transform.position);
transform.rotation = Quaternion.Lerp(transform.rotation,targetRotation,rotationSpeed * Time.deltaTime);``` heres a snippet from the script controlling the cannon in the video
in this one i don't allow it to look up and down (so i use the transform.position.y) of the cannon
or u can just use transform.LookAt(desiredLookTarget);
i use a Lerp to get some smoothing
( the wrong way to use a lerp btw ) and it should be a slerp since im using it for rotations.. ) but it gives u the idea of how to look towards something
hm ok I am getting somewhere
I dont think I really use any lerp methods for rotations
or slerp, so I guess I've been just using methods that probably do a lot of that already
though the method of aiming with the gun's own y and z seems to make it just freeze up
ugh I got something working and then it stopped
lol 😄
upDownPart.transform.LookAt(new Vector3(aiTarget.lastSeenTargetLoc.x, upDownPart.transform.position.y, upDownPart.transform.position.z));```
In this Unity tutorial, I teach you guys how to make an object look at the player whilst rotating on only 1 axis.
#Unity #Unity3D #GameDevelopment
For more Unity tutorials like this or more videos in general - be sure to like, comment, and subscribe for more! 👍
Scripts will be in pinned comment.
Follow me on Twitter:
https://twitter.com/om...
yeah the commented line works but ignores the contraints
the second line just makes it freeze in place
check out this video.. it sounds exactly what u need
my method may be overly complicated for what u need to do
I have tried everything
maybe I can just make it look and then clamp the axes in the next line, will that visually display?
show line 13 of ChangeHeadCosmetic.cs
if u only want it rotating on its X then u need to use its own Y and Z
if u only want it rotating on its Y then u use its own X and Z
and for the Z use its own X and Y
perhaps you should ask in the photon discord
not sure that would work.. clamping it after rotating it.. but it might.. give it a try and see
Yeah mind telling me how i get there i forgot
what you have not done is what we asked. Show the PhotonVRManager SetCosmetic code
but the PhotonVRManager script does\
this?
tbh If you have so little understanding of what you are doing I question the wisdom of your doing it at all
yes, now post it correctly
I have never asked on any discord that is why im confused
!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.
do you not understand what the words Not Implemented mean?
nah ive never experinced this before
well post the code correctly and I shall show you
the exception isn't even happening in their own code, it's happening in some photon asset
indeed, which is where I'm trying to get to
ffs post the damn PhotonVRManager code
no error in photonvrmanager tho
just do it
ffs correctly, that does not even show the correct method
that's not even the correct class or file
📃 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.
Read the instructions
i read the GODDARN instructions im not very good at understanding most stuff
This is a large code block, use the Large Code Blocks instructions
And that's still the wrong class
this is still the wrong code
this is the correct code. just posted incorrectly
What is better: To build generic shaders (e.g., one shader that can change color, grayscale, alpha through parameters) or specific shaders for each individual task?
this is a code channel. perhaps you want to ask your shader related question in #archived-shaders
well, I got it working kind of, but now I can't constrain the angle
to prevent it from looking too far up or down
ok im geniunely wondering how i do this
im currently trying to make a weapon swap system with pickups
ya, that i think u can clamp..
i read instructions i dont understand
what is so hard to understand about posting your code using a paste site
i dont know how to use a paste site
u paste it and hit the save button (it generates a new url)
paste code on site. click save. copy link and send link here
Click link, paste code, post link here
copy and paste that url
paste your code in, save or press the copy option
send the link
ez sauce 🫙
sent the wrong script again 👏
For some reason, even though the code inside of this if statement runs each time it's supposed to (tested with Debug.Log), the particles are sometimes simply not shown, even if the code in the if statement is running. Why does this happen?
This code is running in FixedUpdate, if that helps.
if (Mathf.Abs(rb.velocity.x) > 0 && timeSinceGrounded == 0)
{
dustParticles.Play();
}
it is possible to make a “scriptable obejct variant” like with prefab variants?
you want a job done, do it yourself
/// <summary>
/// Sets a specefic cosmetic
/// </summary>
/// <param name="Type">The type of cosmetic you want to set</param>
public static void SetCosmetic(CosmeticType Type, string CosmeticId)
{
PhotonVRCosmeticsData Cosmetics = Manager.Cosmetics;
switch (Type)
{
case CosmeticType.Head:
Cosmetics.Head = CosmeticId;
break;
case CosmeticType.Face:
Cosmetics.Face = CosmeticId;
break;
case CosmeticType.Body:
Cosmetics.Body = CosmeticId;
break;
case CosmeticType.BothHands:
Cosmetics.LeftHand = CosmeticId;
Cosmetics.RightHand = CosmeticId;
break;
case CosmeticType.LeftHand:
Cosmetics.LeftHand = CosmeticId;
break;
case CosmeticType.RightHand:
Cosmetics.RightHand = CosmeticId;
break;
}
Manager.Cosmetics = Cosmetics;
ExitGames.Client.Photon.Hashtable hash = PhotonNetwork.LocalPlayer.CustomProperties;
hash["Cosmetics"] = JsonUtility.ToJson(Cosmetics);
PhotonNetwork.LocalPlayer.SetCustomProperties(hash);
PlayerPrefs.SetString("Cosmetics", JsonUtility.ToJson(Cosmetics));
if (PhotonNetwork.InRoom)
if (Manager.LocalPlayer != null)
Manager.LocalPlayer.RefreshPlayerValues();
}
this is the method you are calling, your parameters are not right
still wrong script lmao
I don't think so. You can probably make a custom implementation that does that, but nothing out of the box. (Not that I know of at least.)
its supposed to be PhotonVRManager not PhotonVRManagerGUI
you most certainly did not
Ruh roh raggy
you are actually making it impossible to help you. and at this point i definitely won't be attempting to help you further
he's had his answer anyway in spite of his incompetence
right thing
It's like, you want to make a game you should at least be aware how to send the proper script
As pointed out already, yeah You are passing a string string where the method does not take string, string
there is this
internal static void SetCosmetic(string v, string left)
{
throw new NotImplementedException();
}```
it is odd thouse that it throws an Not Implemented exception
but seems generated from IDE / OP
Plus it's internal, idk how you can even use it from outside the library
where you see that?
it's the very last method in the class
scroll down line 375
bingo
good catch 👍
got it, was looking for it and totally missed it
that is what I expected to see
So the reason you're getting the error is because that's literally what the function does.
yeah this def makes the original error make more sense
Damn IDE doing it's job and people not paying attention
Correction: not knowing what they're doing
why cant i use transform.position on this instanciate function
I was trying to be polite, not like me I know but I have my moments
wrong signature
gotta specify a rotation too if you want to provide a position
why did this game object go missing
i have it set to swap out heldweaponprefab to the gun the player just picked up
You destroyed it
It shows that when the object has been deleted (in your project files) or destroyed (in the scene)
The variable has "prefab" in its name, so unless it's badly named and holds an object in your scene, you just deleted your prefab from your files, and forgot to drag-drop a new one
hello guys
I create a new project and get the following error:
Library\PackageCache\com.unity.test-framework@1.1.33\UnityEditor.TestRunner\TestLaunchers\PlatformSetup\PlatformSpecificSetup.cs(19,17): error CS0246: The type or namespace name 'AndroidPlatformSetup' could not be found (are you missing a using directive or an assembly reference?)
can someone help me?
I'm trying to make dust particles that go underneath the player while they run in my platformer game, except that the particles don't always appear when they're supposed to. I use this if statement to tell when the player is running, and this if statement does run when it needs to (tested with the Debug.Log command below). Also, the dust particles do appear to play as dustParticles.isPlaying always returns true while the player is running. However, the particles do not seem to be visible at times even though the code runs when necessary. How can I fix this?
if (Mathf.Abs(rb.velocity.x) > 0.1f && timeSinceGrounded == 0)
{
dustParticles.Play();
Debug.Log(dustParticles.isPlaying);
}
Below is a video example of my problem.
https://gyazo.com/4d10243b06bb4460a33c5c9aff0e0e65
how do i destroy an instance of a prefab without nuking that entire prefab from my project
Instantiate() returns the newly created object, store it in a variable for later use
GameObject instance = Instantiate(prefab)
The code probably doesn't run when necessary
Maybe some code calls Stop() on it right away or too soon so the particles don't have time to spawn.
not code, BUT i have a button that uses an object on DontDestroyOnLoad to get the script from. whenever i reload the scene, the button doesnt have that object attatched. how do I fix that? if u need other context just ask
If anyone can help it would be appreciated.
https://gdl.space/raw/kajurofobu
it does run
rn the log is printing that they're playing even though i can't see them
are you saying problem is with OnCollision2DEnter?
are you sure its runing , put log
there's no stop
Likely your issue lies elsewhere
if it helps in any way, my code is running in FixedUpdate()
Well if there's no stop, the particle system is always emitting!
Yes, everything is running fine except that their is collision, it is supposed to end the race once the object collides with the finish line
it's not looping either
its one of those particles that doesn't loop
show the finish line's inspector
it lasts like 0.1 seconds
Well it should be set to loop, then Play and Pause/Stop when needed
One second
k lemme try that
is there a reason why i still have to click on the screen to get the mouse cursor to listen to CursorLockMode.Locked after escaping the settings menu?
Escape button has an extra behavior in the editor
otherwise you wont be able to get out from editor
It's so you don't lose control of the mouse. It doesn't happen in builds
okay, i wrote some code to change whether the mouse shows up in the menu and locks back when it snot in the menu
i hope that translates well to the build
Here
i dont want to run a build rn loll
Use a different button temporarily in the editor
are the cars rigidbody ? Otherwise you have a big problem
😮 good idea
Yes they are.
then you should move them using the Rigidbody not the transform
otherwise Trigger wont be accurate at all
How do I move them using the RigidBody? Sorry I am still a beginner.
using AddForce or .velocity
The rigidbody should be static too right?
no
Ok
Then what
dynamic
And I should freeze the Y and Z then right?
You would not need Z position nor Z rotation, up to you if u want lock Y too
im stuck, I edited it so many times now, and it continues to read errors, this health script
I've marked a GameObject with DontDestroyOnLoad(), however when I load a different scene and then later on reload the scene with the original DontDestroyOnLoad()-object then both are shown at the same time. Any tips on how to fix it?
did you save?
Yes.
does it come back if you hit Clear
The issue is at the end of line 19
ah shit yeah im blind
There shouldn't be a semicolon at the end of the line
Yes.
nice catch lol
It's throwing the compiler way off, that's why you get a ton of errors
im still getting a list of errors
; means end of a statement
which errors and show current code
"Assets\Scripts\Player\PlayerHealth.cs(20,7): error CS1519: Invalid token '{' in class, record, struct, or interface member declaration
Assets\Scripts\Player\PlayerHealth.cs(21,22): error CS1519: Invalid token '-=' in class, record, struct, or interface member declaration
Assets\Scripts\Player\PlayerHealth.cs(21,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
Assets\Scripts\Player\PlayerHealth.cs(22,26): error CS8124: Tuple must contain at least two elements.
Assets\Scripts\Player\PlayerHealth.cs(22,26): error CS1026: ) expected
Assets\Scripts\Player\PlayerHealth.cs(22,26): error CS1519: Invalid token '<=' in class, record, struct, or interface member declaration
Assets\Scripts\Player\PlayerHealth.cs(26,5): error CS1022: Type or namespace definition, or end-of-file expected
Assets\Scripts\Player\PlayerHealth.cs(28,5): error CS8803: Top-level statements must precede namespace and type declarations.
Assets\Scripts\Player\PlayerHealth.cs(28,5): error CS0106: The modifier 'private' is not valid for this item
"
seems you still have syntax issue then, are you using a configured iDE ?
and did you save changes
Remove the semicolon at the end of line 19 and make sure you saved
I have a modified iDE VS 2019, and did save.
the who what now
from the installer
Why do you need DontDestroyOnLoad? You can fix it by not using that 😄 Otherwise, you probably want it to be a singleton or something 🤔 🤷♂️ Mm... generally, you detect if an instance already exists and you Destroy the old or the new one.
The problem is the Doctor told me to only use the .transform
doesnt seem its configured properly
It is configured (see Solution Explorer), it just hasn't loaded the file
this should say assembly like it does on solution explorer
another scripts there but I don't understand how to remove its past to a current script check
try regen project files
Close the script and open it by double-clicking it from Unity
also that warning is from another script
the original issue was fixed
what, whos the "doctor" ?
if i am making an open world concept first person game, and i have completed movement, and got a mock settings screen up, what should I start to work on next? inventory system? Health or stats? i have no idea, it seems all of them depend on eachother
oh
tanku
I mean my professor
your professor is a quack
you don't move rigidbodies with transform
Bruh I don’t even know why they’re not colliding
Hey, could I have some help creating a delay in my script?
you move Character controllers with transform. transform does not really work with colliders
you realize that transfrom is like teleporting ye? no collisions will work
Thank you.
He told me I can use Trigger2D
your professor probably talked about a character controller, they have built in controller functions for colliders
you still wouldnt move a character controller with transform at all
Yeah I do need it - I'm like 90% sure. Alright, I'll look into singletons. Also, how do I detect if an instance already exists/select which one to destroy? Or is that also linked to the singleton thing?
Sorrey bout the question bombardement x)
oh wait what do you move it by?
Sry lol
either listen to them and do it wrong, or listen to others in this chat n do it properly
If I listen to you guys I will get a 0💀
You should not be moving rigidbodies cars with transform. that makes no sense..
all the collisions will be wonky
lol you probably need velocity or force
talk to your professor and make sure you understand things 🙂
Okay.
Put debug.log inside the TriggerEnter2D and prove to me it works
the best thing You can do is ask clarification to why they are compelled to use transform and not the proper Rigidbody methods
With transform you just clip through walls and stuff
some physics will work even if you move them with transform, I think... it'll just be buggy as frog
it wont be accurate iirc, but it might still trigger a message
Use either velocity or Forces
Basically, I have a problem where I want to have a delay after the player dies. I have made an animation where the player (A Cube) shatters into a bunch of pieces. I want the player to see that animation for 1/2 second, before restarting the scene. Unity tutorials and even ChatGPT are not getting me what I want, since they are telling me to run a coroutine, but since my script deactivates the player cube, a coroutine is out of the question. Is there anything like a delay function in Unity? I'll send my script.
!code
using UnityEngine;
using UnityEngine.SceneManagement;
public class CubeExplosion : MonoBehaviour
{
public GameObject explosionPiecePrefab; // Prefab for the smaller pieces
public float explosionForce = 10f; // Force applied to each piece
public float explosionRadius = 2f; // Radius of the explosion
public float delayInSeconds = 0.5f; // Initialize the delay
private bool hasExploded = false; // Track whether the explosion has occurred
// Call this method to trigger the explosion
public void Explode()
{
if (hasExploded)
return; // Prevent multiple explosions
// Disable the original cube
gameObject.SetActive(false);
// Create smaller pieces
for (int i = 0; i < 27; i++) // 3x3x3 grid of pieces
{
Vector3 randomOffset = Random.insideUnitSphere * explosionRadius;
GameObject piece = Instantiate(explosionPiecePrefab, transform.position + randomOffset, Quaternion.identity);
Rigidbody rb = piece.GetComponent<Rigidbody>();
if (rb != null)
{
rb.AddExplosionForce(explosionForce, transform.position, explosionRadius);
}
}
// Set the explosion flag
hasExploded = true;
}
void Update()
{
if (hasExploded)
{
// Wait here for the specified delay
delayInSeconds -= Time.deltaTime;
if (delayInSeconds <= 0f)
{
// Execute your desired action after the delay
Debug.Log("Half a second has passed!");
// Reload the scene (you can replace this with your actual action)
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
}
}
!code
Yes it would work, but after a while they will break
well yeah, it just wont be accurate at all
you're literally teleporting and letting the physics part "catchup"
My time.Deltatime method does not work for some reason.
No worries. What is that object doing? Singletons are about having a single instance of an script that you can access through a global (static) variable. This way you can easily check if one already exists at the moment a new one is initialized and call Destroy either on the old or the new one.
post code properly
!code
how do i do that sry?
!code
bot is alseep.
!code
its not working right now, read the messages above you
I think you should use a courutine or an async method
Can’t really tell without proper code tho
Coroutine should work fine, async maybe overkill
The player cube is deactivated.
run the coroutine on another object/script
Async methods should work even if the script is destroyed, but I’m not sure rn
But as navarone said it would be overkill
And probably too complex. I mean when you ask ChatGPT to code for you, you're not ready yet
here i grayed out the yRotation lerp and it works with the xRotation
but this is what happens when i dont comment it out
the yRotation should just lerp to the opposite y rotation of the climbingWall
Sometimes I ask chatgpt for things too, when I can’t figure out something. But, after that, I review the code multiple times before actually using that
Afterall, ais are ripetitive in codes or straight out wrong
Alright, yeah it seems like they could be useful in my case.
Basically it's a scroll view in which I instantiate texts to create a sorta scoreboard/highscore board on the main menu. But every time I load a scene the texts just get destroyed. I know there is probably a better way to do it by doing sum like usin binary n serialisation, but the teach wants us to use PlayerPref to save the data. I could dumb the idea down in concept by not displaying it on the main screen, but I think it'd be way cooler if I did.
Are you instantiating the texts in canvas?
They're under the content of the viewport of the scroll view, which itself is under a panel which is under the canvas
if I have an existing git repository, can I just go to VS > git > clone repository to link to it?
It might be appropriate if you were to know how to design it but were too occupied to write the lines of code. However, if you don't know what you're doing and hope chatgpt had done it correctly.. pray that someone else bothers to try to understand chatgpt's logical thinking process.
I know how to code, but I program really late, so I’m tired from work and can’t think properly
idk where to ask this question but. Im trynna make a 2d fighting game and I kinda want my physical colliders not to collide (So 2 bodies can go through each other) but keep the trigger so hp will go down. I was advised with layer collision matrix and my triggers turn off too :/
That’s why I ask chat gpt sometimes
Canvas>Panel>Scroll View>Viewport>Content>[InstantiatedTexts], in simpler terms
collision matrix dictate which pairs of layers are allowed to interact with each other (collision, trigger, callback…). It does not change collision vs trigger
what can i do to stop the collision between 2 objects but keep triggers?
colliders set to Trigger do not exert force, and solely detect via OnTrigger… Callbacks
You should put one of the object in one layer and the other into another layer
you can also use the separate layer overrides to change force vs callback
Explained really badly, but hope you understood
“force send layers”, “force receive layers” are override options to affect which layers actually send/recieve force via this collider, which is separate from collision callbacks
which allows two non-trigger colliders to 1) exert force with other colliders, 2) not exert force between each other, and 3) get OnCollision… messages
understand?
are these the "layer overrides" options?
yes
it seems working now but now i have double interaction between layers 😭
i dunno how it works I have to fix it
you did not explain the problem to fix
because i dont know the problem, it was like "thank you! but i got a new problem so im going to fix it"
layer overrides override the normal settings in the collision matrix
good luck then lol
How do you guys manage your "Main menu" screen in Unity, settings page et.c., is it by simply hiding and showing entire panels, or how do you do it? 🙂
this doesn't seem right
Assets\Scripts\Entity\AI\CompoundTarget.cs(11,18): error CS1540: Cannot access protected member 'Target.Die()' via a qualifier of type 'Target'; the qualifier must be of type 'CompoundTarget' (or derived from it)
@real falcon how does your Target look like?
yes
PRotected means that only a type and types that derive from that type can access that member.
Make it public, make it internal or derive from another class.
but I'm calling that from a child class, so shouldnt I be able to see it?
I feel like Dog should be able to call Animal methods, at least thats how I Remember it in java
@real falcon here's some good explanations on the topic:
https://stackoverflow.com/questions/567705/why-cant-i-access-c-sharp-protected-members-except-like-this
Haven't programmed in Java in like 13 years, so I don't remember 😄
You got a list of Targets that you're calling the method on, not the class itself is accessing the method.
base.Die(); should work though
is there anyway i can do this without making ySmoothRot a global variable?
Added the splines package through package manager, I have spline components available, but when I try to reference splines in my scripts (just using UnityEngine.Splines;) I get: The type or namespace name 'Splines' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?) [Assembly-CSharp]
If I open a script from the splines package it uses that namespace and vscode doesn't complain about it. Is there some extra step when importing the splines package (or any package) to be able to extend/interact with it's code?
It doesn't need to be a global variable. It needs to be initialized before you use it though.
looks like you're assigning yCurrentRot = yRotation (and at the end yRotation = ySmoothRot, so on the next frame they're all the same.
just do
yRotation = Mathf.Lerp(yRotation, yRotation + angleDifference ....
float ySmoothRot = 0f;
ySmoothRot = Mathf.lerp(.....)
then it breaks
oh wait it works
yeah thanks
that would be setting it to 0 every frame tho?
would that also work?
you could just initialize it above
Dog should be able to call animal methods on itself, but you're trying to use a different objects method there
it's not "guaranteed" that it will be set @tender stag you could come around the problem by just initializing the float ySmoothRot and checking with if(ySmoothRot) {code}
Also, I'd use variables in place of those magic numbers: 12, and 2.5. That way, you can edit/test them from the inspector instead of changing and saving the script every time . . .
the solution was to restart unity and vscode 🤷
Im having a purple asset issue ONLY when I build my project. I converted the materials to URP originally to make them work in the editor, but I’m not sure how to fix it in the build…
Unused shaders will be stripped off builds to save disk space. If it's not used anywhere except being loaded by code at runtime, it may have been wrongly stripped off. You can add it to the always included shaders list in the project settings
That's an issue with VSCode. It breaks or does not sync configuration often . . .
I already made a property to get set this variable from a script that's not in a same Game Object with another class
But it still log this error, this means these classes must be in a Game Object to be able to share variable
But I already made a property
WTF is happening
ugh
is there a way to auto populate a return switch? like pressing double tab on a regular switch (enum)?
i dont understand why my destroy script is destroying the entire script instead of an individual gameobject
is there a way to turn my gameobject into an instance within its own script
because you probably did not pass a gameobject?
can i do this or
instantiate it as that type, destroy the instance
what are you trying to do exactly (mechanic)
what is happening instead?
pretty simple
a weapon pickup system
each weapon is a prefab, and when the player picks up a gun it replaces all stats and info of the ground gun with that of the players
ok . can yu show what you're destroying in the code
the player is carrying a prefab version of the gun theyre holding, and that gets spawned in the exact same position as the pickup
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
issues are at line 50
well u need to cache the instance you spawn if thats what u want to destroy
pretty sure we told you earlier how to do that
would this work for my script tho
Hey man
I need your help please
you have the destroy the old one ?
cause what you're doing doesn't make much sense rn
yeah im destroying the gun prefab the player picked up and am replacing it with a instanciated copy of the gun the player is dropping
I already made a property to get set this variable from a script that's not in a same Game Object with another class
But it still log this error, this means these classes must be in a Game Object to be able to share variable
That line
enemyHealth.Health -= damage;
Is line 32
and where did you assign enemyHealth
so what exactly is the original problem ?
Hello guys. How come that when I upload to WebGL, the object does not react to the space key?
webgl does that sometimes
first configure your !ide
Here
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
thats not assignment
and since its private its not assigned anywhere else
for my game i have it so that you press middle click to reload, when i uploaded the game to webgl, the page broke every time you reloaded your gun
it should make no functional difference unless you done wrong logic
Yes, but as there are errors you can't yet. Fix the error (return a number instead), and a suggestion will appear under switch (3 gray dots), hover over it and click the light bulb > "populate switch"
Whoa discord wtf, everything loaded at once
most likely your GhostIsAlive is false
also == true is redudant
Like the message I replied to was the latest one lol
Huh ?
I asked you where you assigned it and you showed me the script, no where did i see its assigned.
Should you by now know the difference between assigment and declaring ?
pretty sure you've done it before lol
They will only appear when there are missing cases. Why did you switch to a regular switch though?
The expression was nice and shorter
You can also trigger the quick actions manually by right-clicking the switch and selecting "Quick actions and Refactorings"
Like Variable A = Value A ?
ahh there you go, thanks
sure thats how you assign things
so where in the code you sent you did that btw?
unity has another way too
Oh you don't have the gray dots so it might just be my own configuration, I fiddled a whole lot with it. Or it might just be with VS 2022? Anyway
yeah prolly because im still using 2019 😂
missin out on intellicode
I'm still on that one too at work but I can't remember on which one it appears. Again maybe it's just my config
will update once i'm done with this game. I'm just afraid it might mess things up.
vs2019 doesn't have intellicode, just intellisense
One thing that's really nice with VS22 is that when you type the completion list is blazing fast, idk what they did but it loads sooo quickly it's unreal, even on my potato laptop
And no, it won't mess anything with your project, you'll just have to tell Unity to use 2022 instead of 2019
Yeah it's the first version that's 64bit
https://paste.myst.rs/68xhtog0
https://paste.myst.rs/rbb0mvk6
https://paste.myst.rs/ugm3g008
Here are the scripts
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
lord.. why are you sending me all this scripts for a simple NRE..
this line throws null
enemyHealth.Health -= damage;
because enemyHealth i null
its not assigned anywhere, you cannot use a component that isn't assigned
What do I have to do ?
I put this script in a Target object
what?
just assign enemyHealth to a component
do you know what [SerializeField] does?
Like this ?
drag n drop n ur done
putting the script there wont do anything..
you need to assign it from wherever you are trying to use it
method or field, you have to assign it somehow
if you have EnemyHealth component on it sure
just use the inspector when possible
You mean both of these script are components of a gameobject ?
Also, make sure you apply the newly added Enemy Health script to your prefab! Otherwise other enemies spawned by code won't have it!
all scripts on a gameobject are Components
No I mean these scripts has to be in a same GameObject ?
GetComponent assumes its this GameObject
unless you specify which component you want to GetComponent from.
eg
someOtherObject.GetComponent<T>();
Today I was working on another game.
And I did the same thing but no error shows up ?
When you put nothing before GetComponent, you can think of it as expanding it to this.gameObject.GetComponent<T>()
Which effectively searches the object this script is on
wdym same thing?
Also the error is from the component you are trying to use isn't present, how does script know which Health component you want
here you're assigning (assuming it finds component)
why is this smooth damp fps dependent?
like when im in the editor minimized window it runs faster
my ui elements (buttons) seem to have a fixed position on the screen so...
and when im in full screen it runs slower
So I have have to declare a game object and do TargetObject.GetComponent ... ?
If you want to get a component on that object, sure thing
well do you have an axis called Input Axis Horizontal ?
I tried doing the Edit-settings-input and i couldnt get it
i dont think so
then you're probably using the wrong one
show the line of code you're using those two
doesnt seem this is the script
or you didnt save
you should probably configure your IDE first if its not already though
idk what that means
also Time.deltaTime is wrong on Inputs mouse
i started today
don't multiply mouse input by deltaTime. mouse input is already frame rate independent so multiplying by deltaTime just makes it dependent on the framerate again causing stuttery camera controls
also obligatory: use cinemachine
best you follow a structured course then !learn
Dyno died
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
what do i multiply it by
just the sensitivity
can anyone help fix the problem with my script? (i think its the script) I posted a thread
why are my ui elements changing position?
did you see the gif?
did you open the thread? 👀
How would i track if i have a certain GameObject (a hammer), currently equipped in this script? ive had a good search and found nothing on the subject.
https://gdl.space/ivapizotiy.cs
also are scriptable objects easier to work with for making inventories?
why did you code position in ? @outer thunder
yes
I followed a tutorial but then this happened
that should not say 0 @silent locust
this tutorial https://www.youtube.com/watch?v=u3YdlUW1nx0
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
In this Unity tutorial, you'll learn about Unity's handy Selectable interfaces (like ISelectHandler, IPointerEnterHandler, et...
what should it say?
at least 20
im not watching a 12 minute video frankly lol
I just use DOTween for all my UI animations
ez pz
good point
guys im trying to make a fighting 2d game and i have 2 scripts rn Actions and Physics. In Physics i have speed ([SerializeField]) and in actions I need to somehow modify that physics speed. how can I do that?
you make a very fine point there thanks
this is all wrong
aw man
brand new projects don't come like this
possible you replaced your project settings
I think you can just copy it over from another project (make a new one)
google says to copy the InputManager.asset file
and replace that
i have no clue what that means
^ any help ^
ima try and watch a tutorial
dont think there is a tutorial for such a specific thing but goodluck ig
all you need to do is replace on file
idk how to do that
You could try using Polyphormism for interactables and for the hammer
you do not even need to do that
why when i debug it prints 0.7071068 Debug.Log(climbingWall.transform.rotation.y);
So you can get directly the script of the hammer
did you loook at the answer from the thread, from a unity empployee ? @silent locust
its clearly 90
what?
like the treads
