#💻┃code-beginner
1 messages · Page 292 of 1
im tring to create a LSystemBrnachPrefab by dragging this asset into the LSystemBrnachPrefab object and i get "no monobehavior scripts in the file or their names do not match the file name"
- Your IDE is not configured
- You might have a compile error somewhere
o I found it I think
'AllowNesting'
yep it works
the variables are starting to get a ridiculous amount of attributes on here
Wait can you explain this to me my brain is fried atm
So the Instantiate<foo>(foo original) returns the references of foo
The hell does that mean
Instantiate returns the new object it created
It would be pretty lame if it didn't
So it destroys it as well or only returns the values of the object?
why would it destroy anything
it creates a copy of the thing you fed in as a parameter
Thats the problem
Why is that a problem?
Yes, this is generics
Bc the player cant be fed as a parameter as the object I want to instantiate is a prefab within a prefab
It wont let me
Did you read my example code? The player is not being fed as a parameter
Also
I did but I didnt understand it sorry
Ill try this time
Getting a cant find collider error even though it exists, I have 2 gameobject in the world both being under the "core class", I have code that loops through a list I made of the "cores" the first iteration goes well but I get the error on the second one even though they are perfect copies other than there index . If only one "core" exists no error is found https://gdl.space/edokayuxaj.cpp
What on earth is Classes.Object.list.Count
the first iteration goes well but I get the error on the second one even though they are perfect copies other than there index
Sharing the error you are receiving is always the best place to start
"an error" is vague
I havent done it yet but I wanted to share the problem that I have
ArgumentNullException: Value cannot be null.
Parameter name: collider
show the full error.
full stack trace
Yes my code example explains exactly how to do this
Cool cool
um how?
Copy it from the console window
what IK package is that?
See the bottom part? That's the full trace
you wuill have to modify the example slightly since you're using GameObject instead of Transform and your script is not called Enemy, you called it something like DogEnemyAI
final ik
but other than that, it will work
ok so what is Ships.cs line 31
have u tried Weight?
The thing is im not using .target. Im doing a different way of the tracking for the enemy so I was confused when reading your code and how to implement it
if (core.Object.GetComponent<CompositeCollider2D>().IsTouching(_object.gameObject.GetComponent<BoxCollider2D>()) & !_object.Stuck)
its like it doesnt exist
you just have to change the variables etc to suit your code
my thing was just an example
using example names
is there a link to the Docs?
in your case it's not called target it's called player.
thnk
ok so _object.gameObject doesn't have a BoxCollider2D
no a composite collider
but its child has one
your code is asking for a BoxCollider2D
if you want the thing from the child, you'd have to get it from the child
oh wait sorry I give wrong info
_object.gameobject is boxcollider, core.object... is composite collider
i wonder why it has poleWeight, and clampWeight, but no weight
when all 3 are in the variable list
oh wait one moment
good good.. idk sometimes third party assets just be like that
probably needs to set via a function b/c it has to do other things in the package for it to work out correctly
hello, i have been trying to acess rigidbody from my script but there is just no sign of iit, any help?
your IDE isn't configured.
!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
Is the transform of an object public so can can i use foo = GetComponent<script> then foo.transform.position?
sure but there's no need to do that
because you can just do transform directly
!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.
What am i supposed to do?
public float countdown; // Initial countdown time in seconds
void Update() {
if (countdown > 0) {
countdown -= Time.deltaTime; // Reduce the countdown by the elapsed time
}
else if (countdown == 0) {
}
// Display the countdown time in seconds
timer.text = countdown.ToString("F0"); // Rounded to whole seconds
}
How can I make it so countdown rounds to the seconds (integers)
as currently just the text ui is rounded
why? you would typically only want the displayed value to be rounded
because when it hits 0 (or the time runs out), the user is meant to have features disabled
follow the linked guide
but currently I can't get countdown at 0 since it skips to negative
don't check if it is exactly 0, just check if it is equal to or less than 0
okay cool thanks
in fact, you don't even need the second condition, just use else
Well you can also do:
countdown = Mathf.Max(0, countdown - Time.deltaTime)``` but yeah in general safer to do `if (countdown <= 0)` in your if statement regardless
its the same.
what's the same?
no rigidbody showing.
Your IDE isn't successfully configured yet
you have to follow all the steps
This may be helpful too https://unity.huh.how/ide-configuration
https://unity.huh.how/ide-configuration/visual-studio-code
its all the same, i chceked the preferences, and the package manager
and checekd if its a proper version or not.
but I still cant see it.
any errors in vs code's console? and if not, have you regenerated project files?
thanks
how can I get a bool value from another scene?
ddol doesnt work apparently?
DDOL works fine
you cant grab a value from a different scene
"scenes" don't hold values
scens have objects in them, and those objects have scripts on them, and the scripts can hold values
public void NextScene() { //Runs on the click of the button
SceneManager.LoadScene(nextScene); //Loads the next scene
player2Turn = true;
DontDestroyOnLoad(player2Turn);
}
so whats wrong with this?
ohh right mb
ddol is for gameobjects
yeah you can't just DDOL a bool lol
if i say ddol gameobject is that the script's object or just the script
i just want the script
What do you think
the objectg
DontDestroyOnLoad(gameObject) < pretty clear what's being DDOL'ed here
no clue
it wouldn't make sense to DDOL just a script. Scripts have to be attached to GameObjects at all time
oh ok
Quick question, is it possible to have multiple camera angles in a 2d game?
You can do whatever you want in any game.
No but how would it work
that's up to you. There are many ways I could imagine it working
"2D game" is also pretty loosely defined
Have you ever heard of Fez?
https://www.youtube.com/watch?v=lrEsNI0aCPk
Explore a serene and beautiful world full of secrets, puzzles and hidden treasures in FEZ, available now on Nintendo Switch! Learn more: https://www.nintendo.com/games/detail/fez-switch
#FEZgame #IndieWorld #NintendoSwitch
Subscribe for more Nintendo fun! https://goo.gl/HYYsot
Visit Nintendo.com for all the latest! http://www.nintendo.com/
...
How can I split this code out so an enemy could walk on "path[i]" - https://gdl.space/apanoqipus.md
is there a way to move all instances of a prefab into one gameobject, so that they can be grouped, and moved to the ddol scene, so they can be loaded again when the scene is re-loaded
so game objects can be put into other gameobjects and then ddol'ed?
also how would you instantiate objects into that particular gameobject
rather than straight into the hierarchy
Using the right overload of instantiate
If you look at the docs, one takes a parent parameter
why is my player not moving when he should. when i press any of the wasd keys the transform changes but i still dont move. if you need a video i can send one. here is the code: https://gdl.space/igoxafubol.cs
any idea what I messed up here? I'm guessing its some very basic logic to do with switching which patrolPoint its heading to but I can't spot the mistake https://gdl.space/omenuyogax.cpp
What if you were moving something other than the player?
you should not be multiplying deltaTime into your AddForce call
nor into this input handling bit:
Input.GetAxis("Horizontal") * (1000 / 10 + (Input.GetAxis("Horizontal") * -100)) * Time.deltaTime
you're multiplying so much deltaTime in here your forces are absolutely tiny
there is no need for deltaTime adjustment with AddForce, least of all in FixedUpdate
Also isn't 1000 / 10 just 100? Why not just write 100
this is very strange
Vector3.ClampMagnitude(rb.velocity, MaxSpeed*Time.deltaTime); < you also don't want it in the clamp here
idk im learning unity and my brain has gone caput for the last week
you are throwing deltaTime in a lot of places randomly
it doesn't belong in any of these places
ill try and fix it upp a litle with the delta time's and se if it works
what magic numbers?
(1000 / 10
* -100)
* 100;
oh ok
most of thiose are just being cancelled out by deltaTime anyway.
Strip this down to almost nothing
simplify it
then build off a simple working foundation
Probably something to do with your patrol method
Log stuff and see what's happening
📃 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.
[SerializeField] bool player2Turn;
void Start() {
player2Turn = GameObject.FindGameObjectWithTag("player2turn");
if (player2Turn == true) {
Camera.main.transform.position.x = 44.6f;
}
}
why does the camera's position not change
whats an overload?
This code nono work and i dont understand why. I touch the enemy and they dont ge tdestroyed
but it still doesnt work
An easily googleable term
It is the same method name with different signatures
is it in a monobehavior
What doesn't work?
AddForce works
Input works
Your code is the broken part
Can you explain please
ill send a video wait a bit
Its in the monobehaviour class
is the code running? Add Debug.Log as the first line of the function to check
Takes Collision2D
Not Collision
Note that Collision is not the right parameter type
okay ill check it
anyone know the issue
this code is not valid C#
it will not compile
how comes?
A gameobject is not a bool for one thing
That's actually not the problem
it's the assignment
You can't modify an anonymous copy of the position vector that will be forgotten instantly
Position is not a variable
You need to do e.g.
Vector3 pos = Camera.main.transform.position;
pos.x = 44.6f;
Camera.main.transform.position = pos;```
so basically too many full stops .
when you do transform.position it is a property that returns a COPY of the position vector
you are not saving that copy anywhere
so changing the x of that copy will be useless
Because the member position is a property and not a field.
okay so basically can't edit the camera's transform without saving it's position as a variable first?
No
You can't modify a component of its position
Only change the whole thing
Vector3 pos = Camera.main.transform.position;
pos.x = 44.6f;
you need to reassign back now
beause pos is a copy
see example
Properties are short handed getter and setter methods for backing fields. Assigning directly to the property is valid. Reading the value of the property is valid. As you access the x component of the vector 3 from the position property, you're invoking the getter and only receiving a copy of the back field (the actual vector 3). If you want to modify the back field, you'll need to assign a value (vector 3 in your case) to the position property as a whole - modifying a component of the returned position will throw an error as the value returned isn't a variable.
what should i log? im assuming the destination position but anything else?
Maybe both positions and has path
See why it's picking one over the other - assuming it's alternating or simply moving towards the wrong destination
@rocky canyon aw yeah new update.
We are back !
https://github.com/MicrosoftDocs/intellicode/issues/535#issuecomment-2040789871
**VScode update # 1.88! **Hugeeee
https://code.visualstudio.com/updates/v1_88
has path never returns true with this no idea how
ok i fixed it not changing directions properly
but when it reached the patrolPoints[0] path, it starts moving towards patrolPoints[1] extremely slowly
same thing happens when it tries to move to patrolPoints[0] again after reaching patrolPoints[1]
is this an automatic update
aye
when i Restart to download i thought it was just the program
my screens went black and then my data light just blinked over and over..
scared me for a second
😮
it was in limbo until i pressed my space key.. and then the monitors came back on.. and the Updated Readme was on VSCode
scary stuff lmao
my computer doesnt do well with Restarts anyway
that would bug me, but only because my laptop is close to death Gpu wise
sometimes i have to hard-shutdown even during Windows Updates
cuz it'll get hung between the boot loader and windows
haha yeah never have any problems on macos. Wind kinda blows
yea yea..
for life..
nah i believe u
always tell the truth even when i lie
whatt
when i create this object, i intend to copy the transform of LSystemBranchPrefab, LSystemBranchPrefaband Base are both at 0,0,0.
it keeps putting the clone at (35.38,-0.06,2.57)
https://hastebin.com/share/wohiquqaji.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Are you mixing up local position and world space position?
i dont think so they should both be 0,0,0
You are using Transform newPlant = Instantiate(plantPrefab, transform.position, Quaternion.identity, transform);
So transform.position is what's being used as the position.
relative to parent?
but you're also making it a child of this object so it should be 0,0,0 local position but possibly not in world space
Where are you seeing the (35.38,-0.06,2.57)?
everything is a t 0,0,0 in my scene
^?
yeah if ur parenting u want localPosition
on line 24 debuglog and in the scene viewer
Hey everyone! I'm learning about Inheritance and Polymorphism. I thought I understood, but when setting up something simple to test the principle, my game does not behave as expected. Would someone mind to help me? 🙂
I have a CubeParent object with a CubeParent script, and a CubeChild with a CubeChild script. The CubeParent script contains two public virtual void methods, which are called in the Update and Start methods.
The CubeChild script calls those 2 parent methods in its own Start and Update scripts. I'm currently not overriding anything.
Strangely enough, my 2 objects do not behave the same.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class CubeParent : MonoBehaviour
{
public virtual void cubeProperties()
{
transform.position = new Vector3(-2, .5f, -2);
transform.localScale = new Vector3(2, 2, 2);
}
public virtual void cubeMovement()
{
transform.Translate(Vector3.forward * 1 * Time.deltaTime);
transform.Rotate(Vector3.up * 10 * Time.deltaTime);
}
private void Start()
{
cubeProperties();
}
private void Update()
{
cubeMovement();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeChild : CubeParent
{
private void Start()
{
cubeProperties();
}
private void Update()
{
cubeMovement();
}
}
And here's a video of game.
😮
Which object is this script on?
https://gdl.space/nejufufuji.cpp any idea what is happening now?
its saying object reference not set but very clearly is in the inspector and was working fine a second ago
agent or patrolpoint is null
how do i instantiate an object and assign it a parent?
woodInstance = Instantiate(woodPrefab, placeholder.transform.position, Quaternion.Euler(0, 0, rotation), woodParent.transform);
this is what i tried
Instantiate has a field for parent
neither are though]
but why does it need to be a transform
because transform Setparent, function wants a transform
That's a different script. The script you sent was LSystemBranch
this is LSystem
yes this will work fine
it had an issue with If (agent.path != null) for some reason
do you have any copies of script
got rid of it and the issue is gone
lsystem branch is on the prefab
Transform is the component responsible for the hiearchy relationships
i dont get it, i just need it grouped in the hierarchy
ohh okay
i posted the link with the video
but i assigned it in the inspector but it still gives me a reference error, saying it is unassigned
that object you have selected is NOT a prefab. You NAMED it Prefab but it's in the scene
prefabs live in your project folder, not the scene
hah im dumb i thought i was a reference to the prefab, i see now
show the code, the error, and the inspector
doesnt really answer the question
why cant i find the create physic material option?
what do you mean copies of the script? as in is it on multiple objects?
scroll down more ?
Show the inspectors of the two objects?
you still have more to scroll
Show the full error message - including filename and line number
UnassignedReferenceException: The variable woodParent of SpawnWood has not been assigned.
You probably need to assign the woodParent variable of the SpawnWood script in the inspector.
UnityEngine.Object+MarshalledUnityObject.ThrowNullExceptionObjectImpl (System.Object obj) (at <d0f92ebb771e4783b0ea9f13bfbe129b>:0)
UnityEngine.GameObject.get_transform () (at <d0f92ebb771e4783b0ea9f13bfbe129b>:0)
SpawnWood.PlaceOnClick () (at Assets/Scripts/SpawnWood.cs:71)
SpawnWood.Update () (at Assets/Scripts/SpawnWood.cs:43)
Think I already found the culprit... 😉
this smells wrong
you have another copy of the SpawnWoopd script in your scene where you didn't assign the variable
otherwise - your code is setting it to null
so now without the error, im still running into the issue that the navmeshagent starts moving incredibly slow after reaching the first point https://gdl.space/awuduxunep.cpp
yeah you have multiple copies
so it's basically running twice on that object
wood (1) looks like it may be an instance of wood
Yeah LOL. It's always funny when you just don't see it!
You might be running multiple coroutines at once
my guess was actually that you would have put BOTH child and parent on it. Not two parents 😉
it wasn't running any coroutines because the player never interacted with the object
Oh Patrol is not in coroutine.
yeah
nah its just i dragged back in a wood instance as the prefab as i changed some properties and wanted to visualize the changes in the scene by keeping it as a instance
ahh
so theres a duplicate script
these indexes should be dynamically changed btw, not sure hard coding index is good idea
are you sure patrolPoints[1].position is correct ? Inspect the agent gizmos during playmode, see where the red destination is set to
search the hiearchy and find out
well a duplicate instance of the script. CHeck
yeah there is
i know but im running into so many issues for this project, and its on a game design module so we arent even graded for how well we code it 😢
ill check the gizmos now
Haha could've definetely happend too! Would you mind helping me with one more thing? I have now added an override. My parent method has 2 lines. I only want to override 1 line, and keep 1 line the same. Should I ONLY write the line I want to change? And will the line I don't change, still work? Because now I have only added 1 line in the override, and it seems the line I don't want to override isn't being taken into account.
The child script:
public override void cubeProperties()
{
transform.position = new Vector3(2, .5f, 2);
}
The parent script:
public virtual void cubeProperties()
{
transform.position = new Vector3(-2, .5f, -2);
transform.localScale = new Vector3(2, 2, 2);
}
When I start my game, the localScale isn't updated on Start in my child object.
is this the red gizmos youre referring to?
if yes then it seems to be working fine
ok so the destination is set correctly , its just not going there?
it is but incredibly slowly
or very slow at least
yes
and i tested it earlier and it does the same thing if it reaches the [1] point
and goes back to [0]
An override completely replaces the virtual method
If you want to still run the code in the base you need to call it in the override.
so it seems to be a case of after reaching the first point it breaks
I wonder if its because the SetDestination is being spammed over and over, I recall last time it give me similiar issues adding it to Update\
public override void cubeProperties() {
base.cubeProperties(); // call the base method
// add extra stuff
transform.localScale = new Vector3(2, 2, 2);
}```
navmesh agent was never like that before, but I think they changed something. Gotta test it again been a while
that could be the case, i tried to do it by vector3.distance but obviously until the distance is higher than 1, it will keep spamming it
I usually do the oppositite , only call SetDestination when the destination was reached
Ah thanks! MSFT VS actually puts that base line whenever I created an override void. now I know why!
how do you check if it has been reached? ive been trying to do that but to no success
which is why im trying with vector3.distance
yeah like if(distance <= agent.stoppingDistance + 0.4f) SetNewDest
I add a bit of threshold to agent.stoppingDistance cause sometimes it doesn't stop at its stopping distance precise
whats the distance variable?
Vector3.distance
ah okay
from agent to destination
and im assuming that would be assigned in update
yeah ideally u want V3.Dist to run every frame
or in my case I do everything in coroutines
so like this if i understand it correctly?
obviously falls apart if i was to add more patrol points but i dont think i will be
yeah should work, you dont need to write that twice though
but yeah like you said because ur hard coding index
actually no wait
i was gonna say, it broke 😭
you're doing it the opposite
how come?
you're saying if its close enough to the stoppingDistance set destination
the agent.dest ==
might be messing with it
yeah cuz i think the floating points dont match
again I just increase indexes is cleaner
nah Vector3s have approximation
for equality check
they're just probably too far when that runs
for some reason since i implemented your distance thing, it now rotates the object around the x axis?
no idea why
this was the bit for rotating
uhh that transform.up don't look right
u can use stopping distance and remaining distance
wouldn't that be transform.forward?
wait ur in 2D?
balance = MoneyManager.p1Balance;
..
balance -= MoneyManager.TriShot_Price; //Subtracts the tri-shot price
what reason could there be for the balance in the moneymanager script to not be subtracted
yes
oh its topdown, ok I see why you mean
no but its a unity 2D project
oh so nvm my suggestion it's for 3d
let me link what I used for 2D navmesh one sec
how did you get navmesh
and followed a tutorial with it let me find it
ohh the 2D navmes extension
any ideas?
- How to create 2D AI pathfinding using the Unity NavMesh components!
- How to have 2D NavMesh Agent in Unity 2022!
GitHub Link: https://github.com/h8man/NavMeshPlus
And don't forget to subscribe for more! ;)
need more context and !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 think i followed this one
but either way it seems to be following the same extension
it should technically work the same
Id try cleaning up the index part first, just incase
this is what happens with transform.forward and transform.up respectively
look at the warning at the corner, I tried to make this ui image into a child so i can have it come along into the next scene when the white image is fading away instead of making it look like it just disappear immediatly when i go over to the next scene but something is not working, how can i turn the ui image object into a child for uicontainer gameobject?
You are subtracting from an unrelated value
Assign it back
i did this for index, not sure if thats what you meant
you are subtracting a variable not from the money manager
yeah didnt realize is 2D topdown myb
transform.up is fine
all you need to do si increase it
no need for if else
h/o ill show u example
damn i dont really get it, like i get it but not really
cause it was working before
unless i changed it
Balance is a completely unrelated variable
It is a separate thing
what does that mean though
Money Manager has a variable
You made a new one called balance
ohh okay
Balance will not affect the variable in MoneyManager at all
yeah since i changed that it stopped working
so the reference doesnt affect the OG
This is a difference between value and reference types
Unless it is a reference type
you need to subtract to the manager itself, balance was local to the weapon class not manager
but computer logic is diff
yeh
If you named it balanceAtThisPoint that would make more sense?
Like, if you need to know what it was before some change so you can revert it, then balance is useful
Otherwise, having the balance variable doesn't really make sense
true
just used it to clean up code
@wintry quarry Can I ask you one more thing about inheritance/polymorphism? Question is: should I include declarations like "public float speed =..." or "private GameManager gameManager" in the child script - or will they also be inherited?
you did use balance to assign the value then subtracted the price on it, you could assign the balance back again but ur just passing the value back and forth many times
if (agent.remainingDistance <= agent.stoppingDistance + 0.4f)
{
currentPointIndex = (currentPointIndex + 1) % patrolPoints.Length;
agent.SetDestination(patrolPoints[currentPointIndex].position);
}```
sorry I took a bit was making dinner
You prob dont need the magic 0.4
its alright dw
if i may, all variables declared from the base class will be inherited, except if it's some private variable or something
thats seems to be working fine thank you
All members of the parent class will be inherited
the agent unfortunately does stop moving though
i genuinely have no idea what might be causing it
strange mine keeps going indefinitely
private variables are also inherited. They are just not accessible from the child class.
oh yes i meant this, like they're just not accessible
it's the
currentPointIndex = (currentPointIndex + 1) % patrolPoints.Length;
could you post what you did with yours? also are you using a rigidbody at all?
sure, thats literally the whole code
You should not be using rigidbody on navmesh agent
yeah i assumed so
public class Agentmove : MonoBehaviour
{
[SerializeField] private NavMeshAgent agent;
[SerializeField] private Transform[] patrolPoints;
private int currentPointIndex;
private void Update()
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
currentPointIndex = (currentPointIndex + 1) % patrolPoints.Length;
agent.SetDestination(patrolPoints[currentPointIndex].position);
}
}
}```
just double checking
ok i got rid of setdestination in start
it moves again
but very slow
you remove the rigidbody ?
Can someone explain why my Debug.DrawLine calls are not working?
T,F,Tmmand Tm are custom classes but can be implicitly converted into Vector2 or Vector3
if (Geometry.intersect(F, T, Tmm, Tm)) {
Debug.Log($"<b><color=#FF0000>Line follow-tail {Geometry.color($"[{F.ToString}-{T.ToString}]", Geometry.EdgeColor)} intersects line Tmm-Tm{Geometry.color($"[{Tmm.ToString}-{Tm.ToString}]", Geometry.EdgeColor)}</color></b>");
Debug.DrawLine(F, T, Color.red, 100f);
Debug.DrawLine(Tmm, Tm, Color.red, 100f);
}```
Of course! Here is my currenet parent class.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeParent : MonoBehaviour
{
//Scoring
private GameManager gameManager;
private int value = 10;
//Enemy speed variable
private float speed = 1.0f;
//Find enemy Rigidbody
private Rigidbody enemyRb;
//Find player GameObject
private GameObject player;
public virtual void Scoring()
{
gameManager.UpdateScore(value);
Debug.Log("Score added = " + value);
Destroy(gameObject);
}
public virtual void Movement()
{
Vector3 lookDirection = (player.transform.position - transform.position).normalized;
enemyRb.AddForce(lookDirection * speed);
}
public virtual void CubeSettings()
{
gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
enemyRb = GetComponent<Rigidbody>();
player = GameObject.Find("Player Main Camera");
}
private void Start()
{
CubeSettings();
}
private void Update()
{
Movement();
}
private void OnMouseDown()
{
Scoring();
}
}
And my child script is empty, and I think everything behaves exactly like the same:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeChild : CubeParent
{
}
The thing I'm now goign to experiment with, is making changes, and seeing if I have to repeat the declerations.
place it before the if statement because you wanna draw the lines first before using them
sorry i was replying to navarone lol
Woops sorry, I see your post towards me above it now. :p
If they're not working in the if statement, why would they work outside of it?
was the condition met and the log printing out?
i'll be waiting here while you all aare helping others
im trying to change rotation like this now but im still getting 90/-90 in x even though im setting agent.updateRotation to false
Generally you want the line to show outside of conditions to verify it is pointing the right way
Being inside an if statement might mean it simply does not run
That's why fake asked if the other debug was running
because when you switch scenes all previous objects are destroyed
2 rotations can be the same, they are converted to quaternion and back to euler for you in inspector. Dont expect the euler angles to be the same numbers, itll still be the same rotation though
dont change euler angles directly btw use Transform.rotation = Quaternion.Euler
and are you sure your pivots are correct too
I thought I was supposed to make a separate GameObject called uiContainer to act as a parent for the UI image. The DontDestroyOnLoad function is then called on the uiContainer object to prevent it from being destroyed when loading the next scene?
well did you do that?
whats the point of setting it to a specific number tho
@wintry quarry Back again. Would you mind helping me one more time? In my parent script I have a private integer value. In the Scoring method I set this integer to 10.
Now in my child script, I want the value integer to be 5.
However, MSFT VS gives this error: "'member' is inaccessible due to its protection level"
What should I do?
Parent script: https://gdl.space/iwuveqesem.cs
Child script: https://gdl.space/lijamolilu.cs
if im setting x to 0 why would it change it to -90 or 90
It needs to be protected to be accessbile from the child
change private to protected
I think so since the uiContainer is a gameobject and the transitionImage is an UI
where did you put uiContainer as DontDestroy
I explained why above, it is converted twice. The rotation is literally the same
Thank you - that worked. I guess that didn't fix everything yet. In my child script, the value added is still the parent value, not the child value.
here's my child script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeChild : CubeParent
{
public override void Scoring()
{
base.Scoring();
value = 5;
}
}
Any more advice you can share? Much appreciated.
Much appreciated. 🙂
except it isn't the same, because x = 0 means the object is visible in 2D space, whereas at -90 its literally rotated to the side and therefore invisible in 2D space
Put it in ddol in awake
why are u rotating on X though?
im not
thats the issue im having
im only trying to rotate on z, but it changes x anyway
you wrote -90 in the inspector
that was to show an example
oh.
of how the 2 rotations arent the same
did you try the line from earlier too
the Quaternion.Euler?
ya
Well yeah I mean look at this:
value = 10;
gameManager.UpdateScore(value);
Debug.Log("Score added = " + value);```
Obviously it's going to use 10
yeah, it has the same result
can you show the scene view with this object selected, with pivots showing in Local mode
protected virtual int GetScoreAmount() {
return 10;
}
protected override int GetScoreAmount() {
return 5;
}```
Maybe this will give you some inspiration^^
(even having a field here makes little sense)
this is after rotated ?
here is out of playmode
yes
like this?
This is definitely not lasting 1 sec as intended, am I using Lerp wrong?
animProgress/duration
Yeah, sure thanks, I am freaking dumb sry
all good!
strange.. can you try transform.Rotate instead
navarone to be completely honest, if the project is to just make a vertical slice so like 1 prototype level, would it just be simpler to scrap navmesh all together and do it script
oh but then id have to code obstacle avoidance myself
😭
yup
Is UIContainer a child of something else?
I can't tell from the hierarchy you showed
let me try that
if that doesn't work, try rotating without the Navmesh agent. See if thats somehow messing with it
although transforms rotation should override any navmesh agent component
like thiss?
or is it Space.World
https://gdl.space/figupagusa.cs nah, the transitionImage is like supposed to be the child and uiContainer the parent
im assuming space.self since im changing its local rotation..?
but the ui container is in canvas
world is fine
they both still result in x rotation being 90 or -90
transform.up method seems to work fine anyway idk what im doing
ahhhhhhhhhhhhhhhh
Oh, ok. Ddol won't work then
Cant't ddol a child
If the parent is NOT in ddol, it gets destroyed, along with all its children
i had it removed
and only used it for chasing player
maybe the reason it slows down/stops after reaching the point is to do with the agent settings i have?
you tried the without the navmesh agent thing ?
oh... then must i move the ui container somewhere else?
Or ddol the canvas.
You can also have more than one canvas
(It is in fact better to have more canvases each with less things)
turn autobreaking off if you dont want slow downs.but yeah check without agent
Ok I have like kinda of a complex question now. How can I tell a bullet that it has already hit an enemy and it cannot hit again?
a simple bool on it
or you could probably pass a Physics.IgnoreCollision after
dependig what ur doing
what if i used normal movement for patrolling and then navmesh for chasing the player?
i think that could work and be way simpler
Let me elaborate. Usually the bullet is just destroyed when hitting an enemy, but I want it to pierce X amount of them sometimes. This is ok, but when used in conjuction with the autoaim system I have right now it is awfull, cause the bullet just gets stuck on the same enemy bouncing around it hitting it multiple times
A bool that tells what? Cause a bullet is meant to able to hit multiple enemies, I would have to keep track of each of them
are you sure the issue is with agent?
not sure if its with the agent but im starting to think it might just be some bug with the extension or something
it works completely fine for chasing the player/returning to the start position
well then you can probably try the ignore collision thing if you don't need it to hit the same collider
it just breaks when changing between the patrol points
like this?
How? I just dissable the collider or what? I don't get this
What is this even supposed to show?
DDOL goes on the Root object
verify its working by checking playmode if they are in separate scene called DDOL
Thanks. I was hoping this part would overeride the value from the parent script, but I guess that's not the case. I also tried creating a "protected virtual int" but that's not allowed.
public override void Scoring()
{
base.Scoring();
value = 5;
}
It certainly gives me inspiration. Haven't figured it out yet, but am working on it.
This is certainly not what I said to do, and it is so crapped that it shows nothing useful
Please stop cropping things so much (as I've said so many times)
well it do works with no warning, but nothing appears in ddol
They are collapsed....
you need to set the value before calling base.Scoring
oh
Like this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeChild : CubeParent
{
public override void Scoring()
{
value = 5;
base.Scoring();
}
}
It doesn't seem to change anything yet. Here's my parent script: https://gdl.space/mecowalagu.cs
of course not becaue the first thing you do in the parent script is set value back to 10
Im trying to make a 2 fighting game (smashbros-like) and i have no idea of how i could make the knockback system
Aha... now that's an eye opener. So does a child script always first run its own script, and then the parent script?
it seems like the image is like behind the other canvas image but the white image doesn't even fade away
This is no longer a code question
Gotta use sorting layers though
it only runs the parent script when you tell it to, which you are doing by using base.
OK got it. Let me think on this... it's quite difficult to grasp!
So I'm kind of learning the hard way, now that my project is getting bigger, the importance of decoupling code. I have a player and I have UI elements like a spedometer and a boost meter. These UI elements read data from a script on the player every frame, like the player's speed or their "boost amount." So the UI elements are grabbing a reference to the player, which is tightly coupling the two. So I want to now learn how to decouple my UI and player, but I'm struggling to find out the best way. I think events are generally frowned upon if its data pretty much being changed every frame. Any other good solutions out there for this kind of thing? Or are events perfectly ok?
not when i said the "doesn't fade away" part though
Ok. Fading out ui seems like a ui thing to me... but whatever you say
events are not frowned upon at all
UI listening to the state of some other object is the perfect use case for events
I see, even if data is being updated every frame? Like for a spedometer? if that's the case, I'll try out events
yes
very cool, ty! 👍
I mean the other option is just having the Ui script read it from the player object each frame
the referential consequences are the same
the UI references the player
the important thing is the player shouldn't reference the UI
hmm... imma try to as in ui ux and look around the scenes
Hey all! Whenever I move, my camera jitters, it's not smooth, and I can't bring myself to move on without fixing it. Im sorry for sounding like a broken record since I know this problem comes up a lot, but ive searched through several forums and other answers and nothing seems to work. Can someone please help?
(I am new to unity by the way)
PlayerMove Script : https://gdl.space/kizodiqeri.cpp
CameraMove Script : https://gdl.space/calahopeba.cpp
CameraControls Script : https://gdl.space/ahevasitej.cpp
if i duplicate a script into another object, if I change some code, will it change it on both objects
i feel like this is an obvious question
but would I need to make another script for this other object
and then change what I want
Duplicate? Perhaps, you mean assign?
the code is the same no matter how many instances you place on objects
idk
ctrl d
on the object with the script inside
You cannot have 2 similar scripts
if (Input.GetKeyDown(KeyCode.F)){
if (canpickup){
if(obj){
itemData = obj.GetComponent<ItemData>();
foreach (GameObject slot in inventorySlots){
Image img = slot.GetComponent<Image>();
img.sprite = itemData.icon;
}
Destroy(obj);
}
}
}```
the icons that exist already I placed, for some reason the icons arent setting (ItemData.icon is a sprite)
The script is not inside the object. An instance of the script is attached to it.
When you duplicate that you will get another copy of the object with its own instance of the same script attached to it
oh okay
well i want one script for player 2 and one for player 1
is there another common way of doing this
that sounds like a bad idea unless they're doing completely different things
The script can be added on multiple GameObjects, you cannot duplicate the same script, as you can have more than one script with the similar name
if they have the same gameplay, they generally should have the same scripts
i have a bool which dictates which player's turn it is
so i could use that
you're putting the same icon in all the slots no?
yeah atm i am
This is usually managed in some sort of GameManager script
if i have the same script in two objects, can they each have different field references
Yes, of course
Of course that's the entire point of the inspector
Imagine having a script called Human. You can assign it to many GameObjects and each will have its own Name, Age, Cat etc.
Why do you have 2 separate scripts for the camera?
One for the actual camera controls (I.e: moving the mouse makes the camera move etc.)
The other for having the camera actually follow my player.
In hindsight, I could very well combine the two, I dont know what I was thinking when I made them separate
Yeah, you really should combine them
I imported an asset called DOTween for a FOV change for dashing but its not working?
but whenever i do using DG.Tweening; it says theres nothing called DG
convince me to download Dotween vs methods like MoveTowards, RotateTowards, and lerps
i only downloaded DOTween cause the tutorial i was following said to do it
Camera movement
Sounds like you didn't install it properly
i probably didnt
or you're typing that in the wrong place
I would go here:
https://dotween.demigiant.com/download.php
download that file
unzip it
Dump it into my assets folder, then follow the instructions in the readme file
- In your code, add "using DG.Tweening" to each class where you want to use DOTween.
- You're ready to tween. Check out the links below for full documentation and license info.```
seem alright I guess if you don't want to shove everything into update, but then you got coroutines too
probably end up using it for some card UI interaction stuff though
i have DOTween downloaded and in my project, i have all the files, but its just not letting me use Using DG.Tweening
ello, made a lil script and attached it to my camera object, but it's not working.
so it's a script for a third-person camera (so it follows my player), but when i play the game it's not exactly third-person.
any help?
using UnityEngine;
public class CamFollowPlayer : MonoBehaviour
{
public Transform player;
// Update is called once per frame
void Update()
{
transform.position = player.transform.position + new Vector3(0, 1, -5);
}
}
Show what you're trying
i already had the files
theres no utility panel that i can find in either one of them
You need to setup it in the dotween panel
Just importing it won't do
how do i do that
where is the dotween panel
Tools and Demignant
im looking through all the files for it and i dont see anything named that
you didn't install dotween correctly then
delete it and make sure you install it from the package manager
and ensure that it's compatible with whatever unity version you're using
whats the simplest way to save scenes
What u mean with Save scene ?
like the player exits a room and it saves the scene
an easy way is to save it local
There are many tutorials on youtube just type unity save/load
Best way is serializing all the info you need to JSON or Binary
It is pretty dang simple too
see #854851968446365696 for what to include when asking for help
do you guys use any websites to organize your ideas for a new unity project?
because whenever i want to practice unity, i always start on a blank slate and make new features as i go without every planning ahead
its easier to making simple coding projects bc u can always build onto them, but with unity its a lot harder to me
Really it depends why you make games and what your objective is
but how do you avoid making your project end up being really convoluted?
It's a massive subject. It's called software engineering. Depending on what context you make games for, it could be something you absolutely require or just something that helps.
One concept that is echoed through software engineering is the concept of scale. If your project is going to be a small game, for example, a Mario clone with just three levels. Then the requirement for planning is significantly less.
But if the plan is to ship a game with many features and you're working in a team of people. All of a sudden the engineering aspect becomes incredibly important
so what about for the purpose of practicing and wanting to add more and more features?
Then there is zero hard requirement for a plan. Unless you're supposed to be practising the engineering aspect.
Then again, I'll ask you a similar question: what are you practising for?
What is your end goal. Then you decide what amount of planning you need
oh i c. well i do want to grow adept at using unity. but maybe more into 2d development like building platformers or roguelikes.
also learning 3d wouldnt hurt either. idk
So, professinally? Or for fun?
for fun
but also for the purpose of selling them too
but as of right now its just for fun
Then I'd say learn the very basics if you are working on your own.
Here's some tools I recommend:
Easier stuff I'd recommend now
- SimpleNote, this is a basic note taking app that works on mobile and PC. Totally free.
- Mircosoft To-Do, this works on Windows and mobile. You can do a to-do list, very simple and easy.
These are for later, maybe bookmark them
- Trello, this is a very famous website for planning. Sort of like a To-Do list.
- Obsidian, this is basically more complicated but has lots of features for planning, graphing and making things look nice (tag systems, markdown, etc)
As for the actual planning, you create a concept of the game (you already have some ideas, platformers or roguelikes for example)
Then you write down each component. Start big, break into smaller bits.
i appreciate the insight jack, thanks
So example
Will the game have combat?
If yes...
- Will the combat be shooting?
- Will the combat be fighting?
- etc etc
Then you start to get to the code planning. Just do this and see what works
If you incorperate a bit of planning into your projects, you will get better and better overtime.
oh i c, thanks a lot for the advice i never thought it out that way as im pretty new to this sort of stuff
if (weaponsCollider == weaponFire.weaponInstance.GetComponent<Collider2D>())
im getting no syntax errors but this doesnt seem 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.
What do you mean "doesn't seem valid" ?
It's fine if it's just one line
cause i was getting an error ab a null value, but one without referencing a script or line, its fixed now though
im having difficulty setting the material to the Default-Diffusion
public Renderer ren;
public Material mat;
void Start()
{
GameObject BaseGO = new GameObject();
BaseGO.AddComponent<UnityEngine.MeshRenderer>();
ren = BaseGO.GetComponent<Renderer>();
// mat = ren.materials;
mat = new Material(Shader.Find("Diffuse"));
// ren.materials = mat;
I want to make a pause game feature inside my GameManager. Right now I am using Action<bool> OnGamePaused How do I make my event observable for changes?
With what?
Debug that find is getting the right object
Find is usually very brittle and should pretty much NEVER be used
https://gdl.space/egasezemew.cs
why does my player jump forever?? gravity doesnt affect him
!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.
Basically anything else. https://unity.huh.how/references
Anyone able to read this?
https://paste.ofcode.org/NzykMeNnjb2PupFVdkSuWF
I have two origin positions, my question is, how could I get the origin's position, and then insert it's x and y values into my nested for loop, when generating each player's building grid? Thanks, if you need anymore context I can explain.
thank you chatgtp
Debug.Log(transform.position);
GameObject BaseGO = new GameObject();
BaseGO.name = "BaseGO";
BaseGO.AddComponent<MeshRenderer>();
BaseGO.AddComponent<MeshCollider>();
BaseGO.AddComponent<MeshFilter>();
ren = BaseGO.GetComponent<Renderer>();
mat = new Material[1];
mat[0] = new Material(Shader.Find("Diffuse"));
ren.materials = mat; ```
Why do AddComponent and then GetComponent?
AddComponent returns the component you add. Just use that
I'm not really sure what you're asking at the end there
But a serialized reference would avoid the need to care what the name is at all. Generally, if you are checking the name of an object for logic reasons, something is going wrong.
in fact you might not even get the same one back
although I guess for Renderer it's guaranteed
This was CGPT generated though so of course it's shite
Jump is only called when the action is pressed. You use jumpingForce when moving, but you do not reset it, so it remains at that value. Also, I would not subscribe using anonymous methods as you cannot unsubscribe from them . . .
ChatGPT seems to just ignore good practices. So annoying
As I said, names should not be relevant here at all. Stop using find
Spits out convoluted code for something really simple
had it my my scrip from before and im blundering around
It cannot ignore what it doesn't know. You'd have to feed the model best practices, then it will use them when providing code. Basically, train your own model . . .
That is almost always the most preferable way to do it
I have only trained an image AI, I guess it's the same concept
Make a singleton
so do i so we are made for each other
And look into additive scene loading
What? Did not know . . . 😲
Just returns the first one it finds.
Generally you only HAVE one (renderer), of course
psl help
Wait, are y'all talking about AddComponent returning the component, or the AddComponent then GetComponent?
The latter one
I may have misread that . . .
Hi there, I'm creating an angry birds clone and have followed a tutorial to set up the basic gameplay. Now I'm feeling stuck in tutorial hell. I'd like to add some abilities like explode on impact or altering the mass but don't know what questions to ask. Does anyone know what concepts, videos, or articles I should look into to begin?
Okay, good; I did misread. I had an AddComponent extension and thought I had to change it . . .
changing the mass is in the rigidbody, if you just learn as you go instead of copying, you'll learn how to make more and more things on your own. I just learned and asked here everytime, im making an angry birds type game rn
can anyone help it is just about referencing the transform position of a gameobject and then starting a nested for loop from it's x property and y property as the initial point of the for loop
It definitely gets that way. That's why avoiding bad practices like find is so important. It takes longer to get going when you set things up properly, but it makes it scale SO much more easily.
Reduce dependencies
Divide responsibilities
Those two can seem to run against each other, but they are very important
!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.
GameObject origin;
Vector3 originPos;
[SerializeField] bool player2Turn;
void Start() {
player2Turn = GameObject.FindGameObjectWithTag("player2turn"); // Finds the gameobject containing the script with the player2turn bool
if (!player2Turn) {
origin = GameObject.FindGameObjectWithTag("Origin");
originPos = origin.transform.position;
} else {
origin = GameObject.FindGameObjectWithTag("Origin");
originPos = origin.transform.position;
}
originPos = origin.transform.position;
GenerateGrid();
}
void GenerateGrid() {
int origin_X = originPos.x
int origin_Y =
if (!player2Turn) {
for (int x = ; x <= width; x += 3) {
for (int y = 0; y <= height; y += 3) {
x_Pos = (x / 10f) - 0.15f;
y_Pos = (y / 10f) - 0.15f;
GameObject spawnedPoint = Instantiate(pointPrefab, new Vector3(x_Pos, y_Pos), Quaternion.identity, pointParent.transform); //Instantiates a new point for each loop cycle
spawnedPoint.name = $"Point {x_Pos} {y_Pos}"; //Names each tile according to their tile co-ords
}}}
else {
for (int x = 2; x <= width; x += 3) {
for (int y = 0; y <= height; y += 3) {
x_Pos = (x / 10f) - 0.15f;
y_Pos = (y / 10f) - 0.15f;
GameObject spawnedPoint = Instantiate(pointPrefab, new Vector3(x_Pos, y_Pos), Quaternion.identity, pointParent.transform); //Instantiates a new point for each loop cycle
spawnedPoint.name = $"Point {x_Pos} {y_Pos}"; //Names each tile according to their tile co-ords
}}}
}
How can I set the first parameter in the x and y for loops to the x and y components of the vector 3 of origin?
So, what was changed?
I still see Find
Did you rename the objects or something?
Also, why the double variables? FullscreenToggle and fullscreenToggle
PauseButton and uiPaused (that last one makes it sound like it should be a bool instead of an object)
public override void OnActionReceived(ActionBuffers actionBuffers)
{
ActionSegment<float> continuousActions = actionBuffers.ContinuousActions;
print(continuousActions[1]);
it keeps printing 0's
idk why
What is ContinuousActions?
See #854851968446365696 it explicitly says not to respond with wdym
I of course have no idea.
R u asking me as in, think about it or what does it mean?
What type is the variable
... it's your code right?
If it's from a package, you should say that
Ok, well, we do not know anything about this code you wrote...
Look at it
What is ContinuousActions?
if u are unable to debug why a value is 0, i have doubts that you wrote these scripts...
We are not mind readers, nor can we look at code you haven't shared
if (Physics.Raycast(Camera.main.transform.position, forwardDirection, out RaycastHit hit, Mathf.Infinity, layerMask))
{
hitPoint = hit.point;
if (ghostBlock == null)
{
ghostBlock = Instantiate(buildingPrefabs[BlockID], hitPoint, Quaternion.identity);
SetTriggersRecursive(ghostBlock.transform);
}
else
{
// Move the ghost block to the snapped position
ghostBlock.transform.position = hitPoint + new Vector3(0, 0.7f, 0);
}```
Any ideas why the block jitters back forth like that? (code snipped)
Sorry, I thought you'd understand with the screenshot
how many people name their stuff the exact same thing as the ML agents thing
I've never used ML agents before, so I've never seen or heard of that
This is code beginner, so I wouldn't assume an advanced package is in play
Lots of people name things the exact same thing as unity components, it's a very common issue
It's a code issue
#1202574086115557446
#💻┃unity-talk is definitely the wrong place
My player's got a one-way ticket to the moon every time they jump, I asked earlier, someone said anonymous methods are lowkey bad and i shouldn't be using them the way i am rn in my lambda functions, but after looking at it for nearly half an hour i still don't see how that's related to my player being infected with this Jumpitis syndrome, but anyway here's the code abyss: https://gdl.space/egasezemew.cs
its kinda messy..
That is a wild nested ternary 🤣
Also, shouldn't the jumpingforce line be affecting the y component? (Line 73)
I feel like the gravity is going weird, but it's really hard to follow honestly
you're doing
newMovementSpeed += jumpingForce *Time.deltaTime; every frame
so off to the moon you go
yeah but I still want the player to move while in air, not just get him locked in the y axis, rigth?
CalculateJump() is not called, and jumpingForceVelocity is not used
using System;
using System.Collections.Generic;
using UnityEngine;
public static class scr_Models
{
#region - Player -
[Serializable]
public class PlayerSettingsModel
{
[Header("View Settings")]
public float ViewXSensitivity;
public float ViewYSensitivity;
public bool ViewXInverted;
public bool ViewYInverted;
[Header("Movement")]
public float WalkingForwardSpeed;
public float WalkingBackwardSpeed;
public float WalkingStrafeSpeed;
[Header("Jumping")]
public float JumpingHeight;
public float JumpingFalloff;
}
#endregion
}
maybe this should help ? It's hard to follow for me too, and I wrote that code
so your jumpingForce never changes
I was only talking about the jump force, which would not affect that of course
Missed that
I'm not sure what this would help with. Or how it is relevant to the issue
Because maybe it's these values that need to be regulated in such a way so that the player can come down again? Idk
Ah. No.
It's the issues that cache and praetor brought up.
Pure logic, not values
I tried many things but I dont know how heigh the player will go before he falls back down
Hey dont mean to be annoying but can somone help me in #🖱️┃input-system ?
Hi there, I'm creating an angry birds clone and have followed a tutorial to set up the basic gameplay. Now I'm feeling stuck in tutorial hell. I'd like to add some abilities like explode on impact or altering the mass but don't know what questions to ask. Does anyone know what concepts, videos, or articles I should look into to begin?
Have you tried using chatgpt at all?
There are pinned resources on this channel
If you haven't definitely do this btw
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
No. I meant click the link the bot brought up, not repeat me haha
Oh lol I see thank you
It works fine when you have a good understanding of the principles involved.
@queen adder we can do without the references to suicide thanks
Saving stuff for scene persistance is not the best. Just use ddol or additive scene loading
Also, you should absolutely stop and set up version control now
Trying to get some experience with events/scriptableobjects like like laid out here: https://unity.com/how-to/architect-game-code-scriptable-objects#what-are-scriptableobjects
One thing I still don't really get. How would I use events to send an event that only a single instance of an object is meant to handle? Or is that not an appropriate use case?
Manual copy backups are a really poor way of doing things.
Get on version control like now
ok so after some tweaks and twists i got to this
https://gdl.space/ekukanidic.cs
I think the player no longer jumps in outer space but now i have the completelly opposite problem where the player is superglued to the ground at all times like a snail on a pavement or smth
Everything works as intented
when I press jump, JumpingForce gets activated, the more I stay on the ground the more it says indeed Is Grounded = True every single second this gets updated and during the start for a few seconds i also get Is Grounded = False, gravity works and then the player just drops on the deck and nothing happens after than, the player's capsule just gets stuck on the ground for eternity like if he had cement shoes on
JumpingForce is apparently broken like my hopes of creating a functional game
Have you considered following an existing player movement tutorial to get something working, studying it, then tweaking from there?
thats a good idea : )
ok so i followed this method of this tutorial, which uses getcomponent<rigidbody> even tho it kind of slows down performance or fps of the game i think...anyway it's good enough but still I think the player has been turned into a snake
I changed the Jump() method and did the same thing this guy does on his code with the rb.AddForce method and still the player will not move
JUMP! JUMP! JUMP!
Check out the Unity3D Fundamentals playlist - http://bit.ly/2FHMP4h
And here's the updated code, (using almost the exact same methods he is using ):
And since im using the GetButtonDown thing I gotta use this name input key thing he uses
Maps[random.Next(0, Maps.Count - 1)]; Shouldn't this code return a random element in the Maps list? Cause I only seem to be getting the first element.
I logged Maps.Count - 1 and it returns one, which is intended
so I don't understand what the issue is
shouldn't the random be capitalised?
but i guess if it had to be it'd show you an error..
Sorry var random = new System.Random(); that code is right before the other one
maybe it can't include the upper bound
lemme try subtracting 0.9
Oh wait. Not sure with next
Range with ints is max exclusive
are you setting a random seed at any point? I forget if you'll still get the same random number sequence otherwise
wait no, it takes an int, so i can't subtract 0.9
ah, that work
thanks!
You can't just mix CharacterController and Rigidbody motion
you'd have to pick one or the other
private void CalculateJump()
{
jumpingForce = Vector3.SmoothDamp(jumpingForce, Vector3.zero, ref jumpingForceVelocity, playerSettings.JumpingFalloff);
}
private void Jump()
{
if (isGrounded && Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
}
jumpingForce = Vector3.up * playerSettings.JumpingHeight;
Debug.Log("Jumping Force: " + jumpingForce.magnitude);
}
}
so something like this? isGrounded without the characterController?
no i don't really see why you would be changing your jumping force in the Jump function
I saw this code earlier
when you posted it earlier
and it didn't make any sense then
and still makes no sense now
What you would do in Jump is add some kind of upwards velocity. Maybe that's what you're trying to do with this jumpingForce variable - if that's the case, it's an exceedingly poorly and confusingly named variable
last I looked at this code you weren't calling your CalculateJump function anywhere either (and why is it called that anyway???)
So i want the code to only play when the play button is clicked, but it works when i click anywehre on the screen for some reason:
Is there any way so that i can only click on the button to transition the scene while also playing the animation?
ok im calling everything here
private void Update()
{
CalculateMovement();
Calculate_View();
CalculateJump();
}
Still can't jump
Why are we back where we started
you need to:
- follow a tutorial that has jumping with CharacterController
or - start actually debugging your code
It's not enough to just put it everywhere. You need to think about how the code is supposed to work and read the logs you're printing and check that things are as you expect
If everything worked as intended you wouldn't be here asking how to make it work
im having an issue with my code where the isFacingRight bool is only changing once the A or D keys are released instead of when pressed. Im using the new input system and curious if there's a way to use it instead of the old input system where I could do on key pressed to do so.
current mapping, not sure if the binding properties have anything to do with it
you'd have to show the rest of the code
i.e. - where is this function getting called from and what is setting move???
top is where move is
i checked in the inspector and when I turn left the move.x is negative 1, when right, its positive one. I was hoping id be as simple as my OnMove() has but evidently not
So quick question.. how do I make a sprite glide after it finishes moving?
what does "glide" mean exactly?
Like 0 gravity, after the player stops inputting on the keyboard for directional movements, the sprite continues goes in that direction
that should be fine - is there a reason you're doing Digital Normalized on the composite?
that doesn't sound like gravity
you mean inertia?
Yeah ig
several options
Oh great
- Use GetAxis - which has smoothing built in
- Simulate velocity manually and change it slowly over time
- Use Rigidbody physics
very true
everything has different characteristics, pros, and cons
no, tbh im not too familiar with the binding properties, but I think that was the default when I set up an up/left/right/down composite @wintry quarry for the WASD keys
cheers thank you
not to mention it also does it with the analog stick which doesnt use digital normalized so not sure
well when are you calling OnMove?/
well to my understanding, using the new input system would allow the game to just run a function based off the name, i.e., thats why I called the function OnMove().
no that's not "the new input system"
that would be a specific mode on the PlayerInput component
so you're using PlayerInput in Send Messages mode?
that's really confusing - why are you mixing up PlayerInput stuff with the manual reading of values from an action map. You should kinda pick one or the other
hello guys i need help im a noob. im doing this program where i ask how many routes, then i ask how many meters the routes are, and then i anwser them what the route is in km. the problem im having is dividing every number by 1000 which im trying to do. it just becoms zero. here is the code and how the program looks like when it runs (its in swedish)
when I did my movement in OnMove() instead it would only trigger once, meaning the game would force u to keep pressing the A or D keys, instead of just holding it. Doing so in fixedupdate allowed for this continious movement. Im still new to this but guess im not understanding in total the new input system.
is that what U mean by manually reading values ?
You're mixing up "handling input" and "moving your character"
they are not the same
Vector2 moveInput;
void OnMove(InputValue inputVal) {
moveInput = inputVal.ReadValue<Vector2>();
}
void FixedUpdate() {
// your movement here using the moveInput vector
}```
Something like this would be typical @rocky vortex
this is not a Unity question
oh yeah i know i thought this was just coding in general but i guess not. sorry!.
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
There's a general C# server^
thanks!!'
I changed my code like you suggested but I still dont see how this fixes my initial question. Is there something else wrong with my movement logic based off the move vector?
is it not working?
ig where is this "manual reading" thing u speak of
and yes it works the same exact way as before I had it
I changed it just for ur suggestion and practice
Debug.Log($"Move value is {move}");```
Step one of debugging your problem^
when you were doing move = inputMap["Move"]... etc before in FixedUpdate
right, initial question aside, there is no change in how the code worked before and after making that change. Back to the question at hand tho, I have been trying to debug it, I have the move values viewable in the inspector, when I click A for left, the x value in the inspector goes to -1, yet the bool remains as isFacingRight = true;
I can see it while the game is running, but its not until after I let go of the key that isFacingRight = false
viewing in the inspector is not the way
use Debug.Log right before the if statement
that will tell you what it actually is when your if statements get ahold of it
also make sure Collapse is NOT turned on in your console
I just turned it on, I was gonna also add a debug.log to print the isFacingRight boolean, and I dont want the move.x debug to clog up the inspector
why do u suggest not turning it on
is it the right values WHEN you expect it?
yes
yes
ok then this part is working fine
you likely have other code changing isFacingRight when you don't want it to
in fact I'm going to throw a hail mary guess here
you probably have if (isFacingRight = true) or something somewhere
which would be the source of your problems
because it's supposed to be == not =
this is the only code using isFacingRight aside from START() where it sets it to true and the declaration of the variable
aren't you reading it somewhere?
otherwise what's the point of it?
why don't you share your full script
!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.
btw to further prove this is working correctly:
Debug.Log($"Move.x is {move.x} and isFacingRight is {isFacingRight}");``` you can put that after this and it should always be correct
what was the shortcut of editing code (tab,gaps etc.) in visual studio
not yet, I havent gotten to that part yet because I would think I need the bool to be properly done first before I could even check it. I dont think the code that depends on the bool would work if I know it will remain false. I added that in, and yes its working I believe, both in the console and the inspector. Logistically I think it was ur suggestion of switching the setting of move in OnMove() instead of fixedupdate. Ty
Not sure what you mean?
You can highlight a bunch of code and press tab, and all of it will indent
I feel like that isn't what you're asking though, but I have absolutely no clue otherwise
So i ending up changing and adding a new line and it works now as intended, a bit strong but ill tone it down so thanks
which shortcut are you looking for
im trying to implement a dash mechanic that uses the player's localscale.x to addforce either neg direction or pos. Im setting that localscale to Vector3(1,1,1) and (-1,1,1) for the left direction. Unity says I cant multiply a Vector3 by a float, even tho im using localscale.x, one of the vector 3 components which the docs says is a float. Anyone have any input?
the error is on the addForce line, 93
is your !IDE configured correctly?
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
I dont think so tbh, I have noticed that VSC isnt giving me errors and have been resorting to using unity not working instead lol
ty
Are you sure that is the error? Because it doesn't look like you are multiplying a vector on the addforce line. It is localScale.x (a float) time dashSpeed, which is a float, right?
it is a float, yes
So what is the error then?
which one should i use for adding delay ? startcoroutine or await task.delay ?
sure
TY, i got my VSC giving me errors now, but the error I had previously remained.
not understanding this part tho, Vector2 and float multiplication
would it have something to do with the error mentioning Vector2 and me setting the localscale to a vector3 ? The move.x speed works, and its a vector2 ... 🤔
dashspeed a float?
AddForce requires a vector 2, but you're multiplying a float by a float
assuming you just want to add force on the x, you want to make a new vector2 and use that value and assign the y to 0
AddForce requires a Vector2
That error makes much more sense than what you said last time 😂
Make a new vector2 using the x if that's what you're looking for
hji everyone, i think this is the right place to ask, i'm having an issue with my code (https://paste.ofcode.org/cDdQzdUaZuJwDFEmycY79D) , in line 25, when i replace the checkCounter() method with the moveChar() method that's defined in the script, then i open unity and try to interact with the buttons i assigned the script to, unity freezes up and i have to close it manually. when i have checkCounter() (which i've written in another script that displays a message when the number of wrong attempts reaches 3) in the else statement it kind of works (it says any button chosen is wrong but at least the method works right) but if its moveChar() it doesnt work at all
yes ty, this should make debugging easier hopefully. And I think what Mao said was pretty clear so thats what ill be attempting next, im just taking a little break rn, ty !
dont use while loops if you're starting out.
stick to forloops as it'll prevent blowing up unity
in this case though you could consider a coroutine with a yield
actually better off just muliplying by deltatime
technically update is already a while loop
update goes off every frame tho right? how do i make it so that it only calls what's in update when eg i press a button?
if button is pressed -> call method and translate
public float speed = 5f;
void Update()
{
if (Input.GetMouseButton(0))
{
transform.Translate(Vector3.right * speed * Time.deltaTime);
}
}```
ohhh, thank you so much!
