我正在尝试根据用户按下下一个按钮来更改图像,但这没有发生
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
private Vector2 targetPos;
public float Yincrement;
public float speed;
public float maxHeight;
public float minHeigth;
public int health = 3;
public int numOfHearts;
public Image[] hearts;
public Sprite heartFull;
public Sprite heartEmpty;
public GameObject effect;
public Image healthDisplay;
private void Update()
{
for (int i = 0; i < hearts.Length; i++)
{
if (i < health)
{
hearts[i].sprite = heartFull;
}
else
{
hearts[i].sprite = heartEmpty;
if (i < numOfHearts)
{
hearts[i].enabled = true;
}
else
{
hearts[i].enabled = false;
}
}
}
if (health <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
{
transform.Translate(0,Yincrement,0)
}
else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minHeigth)
{
Instantiate(effect, transform.position, Quaternion.identity);
transform.Translate(0,Yincrement,0);
}
}
}
var my_image = document.getElementById(main_image);
var image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
var image_index = 1;
function change_image(){
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
答案 0 :(得分:1)
document.getElementById()
需要在其中传递一个字符串。如果main_image
是一个元素而不是字符串,则可能是您遇到的问题。
答案 1 :(得分:0)
看起来您的数组索引设置错误
答案 2 :(得分:0)
您的代码中有2个问题:
1- getElementByID需要一个字符串。 javascript认为main_image是变量名,而不是值。
2-您的数组只有一个元素,因此它的位置是0,而不是1。
下面的代码有效:
var my_image = document.getElementById("main_image");
var image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
var image_index = 0;
function change_image(){
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
<img src="https://www.w3schools.com/jsref/klematis.jpg" id ="main_image">
<button onclick="change_image()"> next </button>
答案 3 :(得分:0)
或者,您也可以查询选择器。 其次,使用addEventListener代替按钮中的onClick。
` 让my_image = document.querySelector(“#main_image”);
let nextBtn = document.querySelector("button")
let image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
let image_index = 0;
const change_image =() => {
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
nextBtn.addEventListener("click", change_image)
` 已经给出了答案,我只是在语法上改进了
答案 4 :(得分:0)
将字符串传递到document.getElementById()。我希望这对您有用。